LeetCode 190 Reverse Bits
=======================
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?
典型的bit manipulation题目,对于bit的异或操作一定要非常熟悉!!!
思路一:
将integer转为binary string,之后按照string的方式进行reverse。显然,这样需要多占用O(N)的空间。
思路二:
直接取int的最后一位d,加入新的int中,再将新的int左移,从而完成从原数据低位到新数据高位的转换!!!这里要注意的是,如何将d加入新的int中,这里需要用到异或(^)操作。新数据在加入d前,通过左移使最后一位保持0,只有当d=1时,新的最后一位才为1。即d与0不同时,0才会变为1,因此采用异或操作。
代码如下:
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 >>> i & 1);
}
return res;
}
}
思路三:
考虑如何像字符串一样,直接反转integer的最高位与最低位。这里可以用bit mask的方式,求取最高位与最低位!!!
public int reverseBits(int n) {
for (int i = 0; i < 16; i++) {
n = swapBits(n, i, 32 - i - 1);
}
return n;
}
public int swapBits(int n, int i, int j) {
int a = (n >> i) & 1;
int b = (n >> j) & 1;
if ((a ^ b) != 0) {
return n ^= (1 << i) | (1 << j);
}
return n;
}