題目描述
顛倒給定的 32 位無符號整數的二進制位。
示例 1:
輸入: 00000010100101000001111010011100
輸出: 00111001011110000010100101000000
解釋: 輸入的二進制串 00000010100101000001111010011100 表示無符號整數 43261596,
因此返回 964176192,其二進制表示形式爲 00111001011110000010100101000000。
示例 2:
輸入:11111111111111111111111111111101
輸出:10111111111111111111111111111111
解釋:輸入的二進制串 11111111111111111111111111111101 表示無符號整數 4294967293,
因此返回 3221225471 其二進制表示形式爲 10101111110010110010011101101001。
在 Java中,沒有無符號整數類型。在這種情況下,輸入和輸出都將被指定爲有符號整數類型,並且不應影響算法的實現,在 Java 中,編譯器使用二進制補碼記法來表示有符號整數。因此,在上面的示例 2 中,輸入表示有符號整數 -3,輸出表示有符號整數 -1073741825。
解題思路
- 思路1 :接口實現,一行代碼,不香,沒有手動實現的樂趣;
- 思路2 :位運算實現,真香,參考大佬分析的思路叭。
代碼實現(Java)
/**
* @author : flower48237
* @2020/3/18 21:25
* @title : LeetCode精選TOP面試題190.顛倒二進制位
* 思路1:接口實現
*/
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
return Integer.reverse(n);
}
}
/**
* @author : flower48237
* @2020/3/18 21:25
* @title : LeetCode精選TOP面試題190.顛倒二進制位
* 思路2:位運算實現
*/
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res = 0;
for (int bitsSize = 31; n != 0; n = n >>> 1, bitsSize--) {
res += (n & 1) << bitsSize;
}
return res;
}
}