Reverse bits of a given 32 bits unsigned integer.
For example, given input43261596
(represented in binary as00000010100101000001111010011100
),
return964176192
(represented in binary as00111001011110000010100101000000
).Follow up:
If this function is called many times, how would you optimize it?
The normal solution is to use bitwise:
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res = 0;
for(int i=0;i<32;i++){
res=(res<<1)+(n&1);
// result shit left, add the last digit of n
n=n>>>1;
// n shift right
}
return res;
}
}
Actually, there is a method in Integer
in Java that reverse the int:
int reverseBits(int n) {
return Integer.reverse(n);
}
To optimize: sbbdy. suggests that divide the int into bytes, reverse each byte and then concate nate into a new int. In reversing the byte, we can use cache to optimize.
// cache
private final Map<Byte, Integer> cache = new HashMap<Byte, Integer>();
public int reverseBits(int n) {
byte[] bytes = new byte[4];
for (int i = 0; i < 4; i++) // convert int into 4 bytes
bytes[i] = (byte)((n >>> 8*i) & 0xFF);
int result = 0;
for (int i = 0; i < 4; i++) {
result = (result<<8)+reverseByte(bytes[i]); // reverse per byte
}
return result;
}
private int reverseByte(byte b) {
Integer value = cache.get(b); // first look up from cache
if (value != null)
return value;
value = 0;
// reverse by bit
for (int i = 0; i < 8; i++) {
value = (value <<1) +((b >>> i) & 1);
}
cache.put(b, value);
return value;
}