Reverse Number II

Reverse bits of a given 32 bits unsigned integer.

Example 1:

Input: n = 00000010100101000001111010011100
Output:    964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:

Input: n = 11111111111111111111111111111101
Output:   3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
 

Constraints:

The input must be a binary string of length 32.

Solution

public uint ReverseBits(uint n) {
    uint result = 0;
    for (int i = 0; i < 32; i++) {
        result <<= 1;
        if ((n & 1) == 1)
            result++;
        n >>= 1;
    }
    return result;
}

This function works by iterating through the bits of n from right to left. In each iteration, it shifts result to the left to make room for the next bit, and then adds the least significant bit of n to result. It then shifts n to the right to process the next bit. This continues until all bits of n have been processed.

The time complexity of the algorithm is O(1). This is because the number of iterations of the loop is fixed at 32, regardless of the input.

The space complexity of the algorithm is also O(1), which means it uses a constant amount of space. This is because weโ€™re only using a fixed number of variables and not any data structures that grow with the size of the input. The integer result and the input n are the only variables being used, and their size does not change with different inputs.

Last updated