Reverse Bits - Problem
Reverse Bits is a fascinating bit manipulation challenge that tests your understanding of binary representation and bitwise operations.

Given a 32-bit unsigned integer, your task is to reverse the order of its bits. Think of it like reading a binary number backwards - the leftmost bit becomes the rightmost, and vice versa.

Example:
Input: 43261596 (00000010100101000001111010011100 in binary)
Output: 964176192 (00111001011110000010100101000000 in binary)


The key insight is that you need to process each individual bit and place it in the corresponding reverse position. This problem is excellent practice for understanding bit shifting, masking, and the relationship between decimal and binary representations.

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 43261596
โ€บ Output: 964176192
๐Ÿ’ก Note: The binary representation of 43261596 is 00000010100101000001111010011100. When reversed, it becomes 00111001011110000010100101000000, which equals 964176192 in decimal.
example_2.py โ€” All Zeros
$ Input: n = 0
โ€บ Output: 0
๐Ÿ’ก Note: All bits are 0, so reversing gives the same result: 0.
example_3.py โ€” Maximum Value
$ Input: n = 4294967295
โ€บ Output: 4294967295
๐Ÿ’ก Note: This is 2^32 - 1, which has all bits set to 1. Reversing all 1s still gives all 1s, so the result is the same.

Visualization

Tap to expand
Bit Reversal Mirror EffectMirror LineOriginal Number031030129...1100Reversed Number031130...1100Algorithm Steps:for i in range(32):result = (result << 1) | (n & 1) # Extract LSB and add to resultn >>= 1 # Shift input rightreturn result # Return reversed bits
Understanding the Visualization
1
Setup
Start with input number and empty result
2
Extract
Take the rightmost bit from input
3
Transfer
Add it to the leftmost position of result
4
Shift
Move both numbers to process next bit
5
Repeat
Continue until all 32 bits are processed
Key Takeaway
๐ŸŽฏ Key Insight: Each bit position i maps to position (31-i) in the reversed result. The shifting approach elegantly builds this mapping by transferring one bit at a time from input to result.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(1)

Always processes exactly 32 bits regardless of input

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only uses a constant amount of extra variables

n
2n
โœ“ Linear Space

Constraints

  • The input must be a 32-bit unsigned integer
  • 0 โ‰ค n โ‰ค 232 - 1
  • You must treat the integer as an unsigned value
  • Follow up: If this function is called many times, how would you optimize it?
Asked in
Apple 45 Microsoft 38 Amazon 32 Google 28
68.5K Views
Medium Frequency
~15 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen