,  

Reverse bits of a given 32 unsigned bits integer

Problem: Given an unsigned integer, reverse all bits of it and return the number with reversed bits.

For example:
Input: n = 43261596
Output: 964176192
The binary representation of 43261596 is 00000010100101000001111010011100.
Reversing the bits we get, 00111001011110000010100101000000 which is equivalent to 964176192.

Input: n = 1
Output: 2147483648
The binary representation of 43261596 is 00000000000000000000000000000001.
Reversing the bits we get, 10000000000000000000000000000000 which is equivalent to 2147483648.
The easiest and most efficient approach is reversing bit by bit.
#include <bits/stdc++.h>
using namespace std;

/* function return the reversed bits integer */
unsigned int revBits(unsigned int num)
{
    unsigned rev_num = 0;
    int siz = sizeof(num) * 8;

    for (int i = 0; i < siz; i++)
    {
        rev_num <<= 1;
        rev_num |= num & 1;
        num >>= 1; 
    }

    return rev_num;
}

/* driver function */
int main()
{
    int unsigned a;
   
    a = 1;
    cout<<revBits(a)<<"\n";

    a = 105;
    cout<<revBits(a)<<"\n";

    return 0;
}
Output:
2147483648

2516582400
Time Complexity: O(logn) and Space Complexity: O(1)