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


Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   uint32_t reverseBits(uint32_t n) {
      uint32_t ans = 0;
      for(int i = 31; i >= 0; i--){
         ans |= (n & 1) <<i;
      return ans;
   Solution ob;
   cout << ob.reverseBits(0b00000000000000000000001001110100);