LeetCode 190 Reverse Bits

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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容