1. 程式人生 > 其它 >LeetCode 0190 Reverse Bits

LeetCode 0190 Reverse Bits

原題傳送門

1. 題目描述

2. Solution 1

1、思路分析
逐位顛倒
We first initialize result to 0. We then iterate from
0 to 31 (an integer has 32 bits). In each iteration:
We first shift result to the left by 1 bit.
Then, if the last digit of input n is 1, we add 1 to result. To
find the last digit of n, we just do: (n & 1)
Example, if n=5 (101), n&1 = 101 & 001 = 001 = 1;
however, if n = 2 (10), n&1 = 10 & 01 = 00 = 0).

Finally, we update n by shifting it to the right by 1 (n >>= 1). This is because the last digit is already taken
care of, so we need to drop it by shifting n to the right by 1.

2、程式碼實現

package Q0199.Q0190ReverseBits;

/*
    We first initialize result to 0. We then iterate from
    0 to 31 (an integer has 32 bits). In each iteration:
    We first shift result to the left by 1 bit.
    Then, if the last digit of input n is 1, we add 1 to result. To
    find the last digit of n, we just do: (n & 1)
    Example, if n=5 (101), n&1 = 101 & 001 = 001 = 1;
    however, if n = 2 (10), n&1 = 10 & 01 = 00 = 0).

    Finally, we update n by shifting it to the right by 1 (n >>= 1). This is because the last digit is already taken
    care of, so we need to drop it by shifting n to the right by 1.
 */
public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        if (n == 0) return 0;
        int result = 0;
        for (int i = 0; i < 32; i++) {
            result <<= 1;   // 把當前結果儲存到result的最低位
            if ((n & 1) == 1) result++;
            n >>= 1;
        }
        return result;
    }
}

3、複雜度分析
時間複雜度: O(32) = O(1)
空間複雜度: O(1)

3. Solution 2

1、思路分析
位運算分治
若要翻轉一個二進位制串,可以將其均分成左右兩部分,對每部分遞迴執行翻轉操作,然後將左半部分拼在右半部分的後面,即完成了翻轉。
由於左右兩部分的計算方式是相似的,利用位掩碼和位移運算,可以自底向上地完成這一分治流程。

對於遞迴的最底層,需要交換所有奇偶位: 取出所有奇數位和偶數位;將奇數位移到偶數位上,偶數位移到奇數位上。類似地,對於倒數第二層,每兩位分一組,按組號取出所有奇陣列和偶陣列,然後將奇陣列移到偶陣列上,偶陣列移到奇陣列上。

2、程式碼實現

public class Solution {
    private static final int M1 = 0x55555555; // 01010101010101010101010101010101
    private static final int M2 = 0x33333333; // 00110011001100110011001100110011
    private static final int M4 = 0x0f0f0f0f; // 00001111000011110000111100001111
    private static final int M8 = 0x00ff00ff; // 00000000111111110000000011111111

    public int reverseBits(int n) {
        n = n >>> 1 & M1 | (n & M1) << 1;
        n = n >>> 2 & M2 | (n & M2) << 2;
        n = n >>> 4 & M4 | (n & M4) << 4;
        n = n >>> 8 & M8 | (n & M8) << 8;
        return n >>> 16 | n << 16;
    }
}

3、複雜度分析
時間複雜度: O(1)
空間複雜度: O(1)