Reverse Bits in C++


Suppose we have one unsigned number x, and we can easily find the binary representation of it (32bit unsigned integer). Our task is to reverse the bits. So if the binary representation is like 00000000000000000000001001110100, then reversed bits will be 00101110010000000000000000000000. So we have to return the actual number after reversing the bits

To solve this, we will follow these steps −

  • Suppose n is the given number
  • let answer := 0
  • for i := 31 down to 0:
    • answer := answer OR (n AND i), and shift it to the left i times
    • n := n after right shifting 1 bit
  • return answer

Example

Let us see the following implementation to get better understanding −

 Live Demo

class Solution {
   public:
   uint32_t reverseBits(uint32_t n) {
      uint32_t ans = 0;
      for(int i = 31; i >= 0; i--){
         ans |= (n & 1) <<i;
         n>>=1;
      }
      return ans;
   }
};

Input

00000000000000000000001001110100

Output

775946240 (00101110010000000000000000000000)
raja
Published on 16-Jan-2020 09:40:14
Advertisements