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:
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.
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
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
โ Linear Growth
Space Complexity
O(1)
Only uses a constant amount of extra variables
โ 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?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code