Reverse Bits
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Bit Manipulation.
Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
Examples
Input: n = 43261596
Output: 964176192
43261596 (00000010100101000001111010011100) reversed is 964176192 (00111001011110000010100101000000).
Approach 1
Level I: Brute Force (Iterate and Shift)
Intuition
Iterate through each of the 32 bits of the input. In each step, shift the result left and add the last bit of the input. Then shift the input right.
Thought Process
- Initialize
res = 0. - Loop 32 times:
- Check the last bit of
n:n & 1. - Shift
resleft and add that bit:(res << 1) + (n & 1). - Right shift
nby 1.
- Check the last bit of
- Return
res.
Pattern: Bitwise Result Construction
⏱ O(1) - Always 32 iterations.💾 O(1) - Constant extra space.
Approach 2
Level II: Byte-by-Byte Lookup (Caching)
Intuition
A 32-bit integer consists of 4 bytes. We can precompute or manually reverse the bits for each byte (8 bits) and then combine them. This is faster when multiple calls are made as the byte reversals can be cached.
⏱ $O(1)$ - Proportional to number of bytes (4).💾 $O(1)$ - Small lookup table or fixed reversal logic.
Approach 3
Level III: Optimal (Divide and Conquer)
Intuition
We can reverse the bits using a series of mask and shift operations. First, swap adjacent bits, then swap adjacent pairs, then adjacent nibbles (4 bits), and so on.
Thought Process
- Swap bits 1-by-1:
n = ((n & 0xAAAAAAAA) >>> 1) | ((n & 0x55555555) << 1) - Swap bits 2-by-2:
n = ((n & 0xCCCCCCCC) >>> 2) | ((n & 0x33333333) << 2) - Swap bits 4-by-4:
n = ((n & 0xF0F0F0F0) >>> 4) | ((n & 0x0F0F0F0F) << 4) - Swap bits 8-by-8:
n = ((n & 0xFF00FF00) >>> 8) | ((n & 0x00FF00FF) << 8) - Swap bits 16-by-16:
n = (n >>> 16) | (n << 16)
Pattern: Parallel Bit Processing
⏱ O(1) - Constant number of bitwise operations.💾 O(1) - Constant space.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.