Reverse Bits

Reverse 32 bits of an unsigned int — shift the result left and OR with the low bit of the input each step.

Easy
Time O(32) Space O(1)
LeetCode
2 min read
bit-manipulation

Problem#

Reverse the bits of a 32-bit unsigned integer.

Examples#

  • 0000001010010100000111101001110000111001011110000010100101000000 (i.e., 43261596964176192).
  • 1111111111111111111111111111110110111111111111111111111111111111.

Constraints#

  • Input is a 32-bit unsigned integer.

Approach#

Loop 32 times: shift ans left by 1, OR in the low bit of n, shift n right by 1.

Solution#

Reverse Bits
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t ans = 0;
for (int i = 0; i < 32; ++i) {
ans = (ans << 1) | (n & 1u);
n >>= 1;
}
return ans;
}
};

Editorial#

This is a “feed the bits in reverse order” pattern. Each iteration consumes the LSB of input and deposits it as the LSB of output, then both shift — exactly mirroring the bit order. A divide-and-conquer mask-swap version reverses in five O(1) steps for the speed-conscious.

Complexity#

  • Time: O(32) constant.
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.