Reverse Bits
Master this topic with zero to advance depth.
Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
Examples
43261596 (00000010100101000001111010011100) reversed is 964176192 (00111001011110000010100101000000).
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
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.
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
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.