Cover image for Interview Classic 150 Questions P190 Reverse Bits

Interview Classic 150 Questions P190 Reverse Bits


Timeline

timeline

2025-11-25

init

bit manipulation

Title:

Reversing in place is cumbersome; you can use a temporary variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int reverseBits(int n)
{
unsigned int r = 0;
for (int i = 0; i < 32; i++) {
r <<= 1;
r |= (n & 1);
n >>= 1;
}
return r;
}
};