# Reverse Bits in C++

PythonServer Side ProgrammingProgramming

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
• 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

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
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;
}
};
main(){
Solution ob;
cout << ob.reverseBits(0b00000000000000000000001001110100);
}

## Input

0b00000000000000000000001001110100

## Output

775946240
Published on 16-Jan-2020 14:10:14