1 题目
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
接口
public int reverseBits(int n)
uint32_t reverseBits(uint32_t n)
2 思路
简单写一下,Java的思路。Java中是没有无符号整数的,只有有符号的int(0x80000000 ~ 0x7fffffff)。
&和|操作的结合使用。
复杂度
Time: O(n) Space: O(1)
3 代码
public int reverseBits(int n) {
int res = 0;
for (int i = 0; i < 32; i++) {
int bit = (n >> i) & 1;
res |= bit << (31 - i);
}
return res;
}
4 总结
(n >> i) & 1是取余数的好方法,不用借助额外的空间。