1. 程式人生 > >leetcode 190.顛倒二進位制位

leetcode 190.顛倒二進位制位

顛倒給定的 32 位無符號整數的二進位制位。

示例:

輸入: 43261596
輸出: 964176192
解釋: 43261596 的二進位制表示形式為 00000010100101000001111010011100 ,
     返回 964176192,其二進位制表示形式為 00111001011110000010100101000000 

進階:
如果多次呼叫這個函式,你將如何優化你的演算法?

思路一:將數 n 與 1 進行 & 運算,得到末尾的數字,並且存入陣列中,進行 32 次。然後將陣列中的數字換成 十進位制,這裡要注意的是可能會溢位,要使用 long ,最後強制轉型為 int。

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int i = 0;
        int[] result = new int[32];
        int j = 31;
        long sum = 0;
        while(i < 32){
            result[j--] = (n&1);
            n = n>>1;
            i++;
        }
        for(int k = 31;k >= 0;k--){
            sum += result[k] * Math.pow(2,k);
        }
        return (int)sum;
    }
}

思路二:不使用另外的陣列儲存每一次的結果,使用 r 即可。用 n & 1 得到 數 n 的末尾數字,然後將他與 r 進行或運算,最後將 r 右移 32 - i 位即可。>> 有符號數右移,>>> 無符號數右移。

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
		int r = 0;
        int i = 0;
        while(n != 0) {
            r = r << 1;
            r = r | (n & 1);
            n = n >>> 1;
            ++i;
        }
        return r << (32 - i);
    }
}