190. Reverse Bits
At a Glance
- Topic: bit-manipulation
- Pattern: Bit ops / shift accumulate (Bit Manipulation)
- Difficulty: Easy
- Companies: Amazon, Apple, Microsoft, Google, Adobe
- Frequency: High
- LeetCode: 190
Problem (one-liner)
Reverse the bit order of a 32-bit unsigned integer and return the value (LeetCode treats as unsigned for this problem).
Recognition Cues
- "Reverse bits" of fixed width
- Build result by shifting in bits from LSB to MSB of output
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force — stringify bits —
O(32)with extra space. - Optimal — iterative bit extraction and push —
O(32)time /O(1)space.
Optimal Solution
Go
package main
func reverseBits(value uint32) uint32 {
var result uint32 = 0
for shift := 0; shift < 32; shift++ {
result <<= 1
result |= value & 1
value >>= 1
}
return result
}JavaScript
function reverseBits(value) {
let result = 0;
let remaining = value >>> 0;
for (let shift = 0; shift < 32; shift++) {
result <<= 1;
result |= remaining & 1;
remaining >>>= 1;
}
return result >>> 0;
}Walkthrough
Small pattern on 8 bits for intuition — mirror each incoming least significant bit into growing result.
Invariant: after shift steps, result holds the reversed lower shift bits of the original in its upper construction.
Edge Cases
- All zeros / all ones
- Palindrome bit patterns
Pitfalls
- Forgetting exactly 32 iterations
- JS signed vs unsigned — use
>>>/>>> 0return
Similar Problems
- 191. Number of 1 Bits — traverses set bits differently.
- 007. Reverse Integer — decimal reverse (canonical math topic).
Variants
- Reverse within subrange of bits.
- Swap endianness for specific sizes (16/64).
Mind-Map Tags
#reverse-bits #shift #unsigned #fixed-width #bit-ops
Last updated on
Spotted something unclear or wrong on this page?