Skip to main content
PreparationZone Logo
PreparationZone
Back to Coding

Coding · Easy · Free

Reverse bits of a 32-bit integer

CodingBit ManipulationFresher
Model answer

Approach

  • Shift result left, take lowest bit of n, shift n right.
  • Repeat 32 times.

Java Solution

Java
public int reverseBits(int n) {
    int ans = 0;
    for (int i = 0; i < 32; i++) {
        ans <<= 1;
        ans |= (n & 1);
        n >>>= 1;
    }
    return ans;
}
Complexity
TimeO(1)
SpaceO(1)
Interview tip: Networking and UUID v4 discussions sometimes need bit reversals.