Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Solution 1:
// you need treat n as an unsigned value
public int reverseBits(int n) {
int result=0;
for(int i=0; i<32; i++){
result = (result<<1)|(n&1);
n = n >> 1;
}
return result;
}
Optimized for repeat usage, solution 2:
// optimization idea: cache reverse numbers for all int numbers, but space complexity if O(2^32)
// idea is to make reverse int into 4 reverse byte, in this case only cache O(2^8)
public int reverseBits(int n) {
byte[] temp = new byte[4];
for(int i=0; i<4; i++, n=n>>>8){
temp[i] = (byte)n;
}
int result=0;
for(int i=0; i<4; i++){
result = (result<<8) | ( reverseBytes(temp[i]) & 0xff );
}
return result;
}
public byte reverseBytes(byte n) {
byte oldn=n;
Byte result = cache.get(n);
if(result!=null) return result;
result=0;
for(byte i=0; i<8; i++){
result = (byte)((result<<1)|(n&1));
n = (byte)(n>>1);
}
cache.put(oldn,result);
return result;
}