题目:Reverse bits of a given 32 bits unsigned integer.
java需要注意的是:
(1)Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
(2)In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above the input represents the signed integer -3 and the output represents the signed integer -1073741825.
- 一个整型有4个字节,每个字节八个比特位(一个Byte),将整型进行分解分别对每个Byte进行翻转,再合并就可以实现对原数字比特位的翻转。
for (int i = 0; i < 4; i++) {
ret <<= 8;
ret |= reverseByte((byte) (n & 0b11111111));
n >>= 8;
}
如上所示,其中(n & 0b11111111)是为了截取转换成整型的后八位,0b代表后面的数字是二进制,和n相与之后会自动转换为整型,如果不对后八位进行截取,那么前面的24位会补1会造成结果的错误。前面的Byte是为了类型转换。
完整的代码实现:
public static void main(String[] args) {
int n = 43261596;
System.out.println(reverseBits(n));
}
private static Map<Byte, Integer> cache = new HashMap<>();
public static int reverseBits(int n) {
int ret = 0;
for (int i = 0; i < 4; i++) {
ret <<= 8;
ret |= reverseByte((byte) (n & 0b11111111));
n >>= 8;
}
return ret;
}
private static int reverseByte(byte b) {
if (cache.containsKey(b))
return cache.get(b);
int ret = 0;
byte t = b;
for (int i = 0; i < 8; i++) {
ret <<= 1;
ret |= t & 1;
t >>= 1;
}
cache.put(b, ret);
return ret;
}