In java there is >> and >>>, the difference is >>> is used for unsigned right shift. For all the 32 bits in the unsigned int n, we read one bit by one bit. Add to the new int result, then left shit one bit to let the new tail bit coming in.
1
2
3
4
5
6
7
8
9
10
11
12
publicclassSolution{
// you need treat n as an unsigned value
publicintreverseBits(int n){
int rst = 0;
for (int i = 0; i < 32; i++) {
rst <<= 1;
rst += n & 1;
n >>>= 1;
}
return rst;
}
}
optimize
If multiple calls to the function, we could use some Map to cache the intermediate result. For this question, we can divide one integer into 4 bytes and cache the reversed bits of each bytes. If later we see the same byte, we don’t need to re-compute the result again.