Leetcode 190 Solution

This article provides solution to leetcode question 190 (reverse-bits)

https://leetcode.com/problems/reverse-bits

Solution

class Solution {
public:
    int swapBit(int n, int i, int j)
    {
        int a = (n >> i) & 1;
        int b = (n >> j) & 1;

        if (a == b)
            return n;

        return n ^ ((1 << i) | (1 << j));
    }

    uint32_t reverseBits(uint32_t n) {
        for (int i = 0; i < 16; i++)
        {
            n = swapBit(n, i, 31 - i);
        }

        return n;
    }
};