result = (result << 1) | (n & 1); n >>>= 1; repeat 32 times.
Approach 1
class Solution {
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
result = (result << 1) | (n & 1);
n >>>= 1;
}
return result;
}
}
Verdict: Integer.reverse(n) does it too.
Before you submit
Edge cases and common mistakes
Test these inputs
Negative input (top bit set)
0
Mistakes people make
Using >> (copies the sign bit into the result).
Interview
Follow-up questions
How would you speed this up for millions of calls?