DSA · Bit Manipulation · #148
Reverse Bits
Module 50 · difficulty 2/5·⏱ 30:00starts on first keystroke
Implement `reverseBits(n)` that reverses the bits of a given 32-bit **unsigned** integer `n` and returns the resulting 32-bit unsigned integer. The input `n` is a non-negative integer in the range `[0, 2^32 - 1]`. Treat it as a 32-bit binary string, reverse the order of all 32 bits, and return the value of that reversed string as an unsigned integer. In JavaScript, bitwise operators interpret numbers as 32-bit **signed** integers, so use `>>> 0` to coerce the final result back to an unsigned value.
Examples
n = 43261596→964176192— 00000010100101000001111010011100 reversed is 00111001011110000010100101000000.n = 4294967293→3221225471— 11111111111111111111111111111101 reversed is 10111111111111111111111111111111.n = 1→2147483648— The lowest bit moves to the highest position.
Constraints
- · The input is a 32-bit unsigned integer: 0 <= n <= 2^32 - 1.
- · Return a 32-bit unsigned integer.
- · Follow-up: if this function is called many times, how would you optimize it (e.g. caching bytes)?
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.