1.Reverse Bits

Reverse bits of a given 32 bits unsigned integer.

Example 1:
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000
class Solution
{
public:
    uint32_t reverseBits(uint32_t n)
    {

        bitset<32> b(n);

        int start = 0;
        int end = 31;
        while (start <= end)
        {
            if (b[end] == 1 && b[start] == 0)
            {
                b.set(start, 1);
                b.set(end, 0);
            }
            else if (b[end] == 0 && b[start] == 1)
            {
                b.set(start, 0);
                b.set(end, 1);
            }

            start++;
            end--;
        }

        return b.to_ulong();
    }
};

Time Complexity: O(n )

Reverse Bits when an integer is given and return an integer

unsigned int revBits(unsigned int n)
{

    int rev = 0;
    while (n > 0)
    {
        // bitwise left shift
        // 'rev' by 1
        rev <<= 1;

        // if current bit is '1'
        if (n & 1 == 1)
        {
            rev = rev ^ 1;
        }

        // bitwise right shift
        // 'n' by 1
        n >>= 1;
    }
    return rev;
}

Last updated