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轉(zhuǎn)為binary string,之后按照string的方式進行reverse。顯然,這樣需要多占用O(N)的空間。
思路二:
直接取int的最后一位d,加入新的int中,再將新的int左移,從而完成從原數(shù)據(jù)低位到新數(shù)據(jù)高位的轉(zhuǎn)換?。?!這里要注意的是,如何將d加入新的int中,這里需要用到異或(^)操作。新數(shù)據(jù)在加入d前,通過左移使最后一位保持0,只有當d=1時,新的最后一位才為1。即d與0不同時,0才會變?yōu)?,因此采用異或操作。
代碼如下:
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;
}
}
思路三:
考慮如何像字符串一樣,直接反轉(zhuǎn)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;
}