快轉到主要內容
leetcode 190 - Reverse Bits

leetcode 190 - Reverse Bits

·
類別 
Leetcode
標籤 
Java Leetcode Easy Bit Problem Blind75
Eason Chiu
作者
Eason Chiu
一個不做筆記就容易忘記的工程師
目錄

題目
#

leetcode 190 - Reverse Bits (題目說明請點連結)

題目簡述
#

反轉一個 32 位無符號整數的二進制位。

範例
#

Example 1:

Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Explanation: 輸入的二進制數 00000010100101000001111010011100 反轉後得到 00111001011110000010100101000000,轉換為十進制是 964176192。

Example 2:

Input: n = 11111111111111111111111111111101
Output: 3221225471 (10111111111111111111111111111111)
Explanation: 輸入的二進制數 11111111111111111111111111111101 反轉後得到 10111111111111111111111111111111,轉換為十進制是 3221225471。

Example 3:

Input: n = 00000000000000000000000000000000
Output: 0
Explanation: 輸入為 0,反轉後仍為 0。

解題思路
#

這題要求我們將一個 32 位無符號整數的二進制位進行反轉。我們需要從右到左逐位取出原數的每一位,然後從左到右重新組合成新的數。

解法
#

位運算反轉法(Bit Manipulation Approach)

  1. 初始化結果變數 res = 0
  2. 遍歷 32 位,每次處理一位:
    • 將結果左移一位,為新位騰出空間
    • 取出原數的最右一位,加到結果上
    • 將原數右移一位,準備處理下一位
  3. 返回反轉後的結果

步驟
#

  • 初始化:
    • res = 0(存儲反轉後的結果)
  • 逐位處理:
    • 迴圈 32 次(32 位整數)
    • res <<= 1:結果左移一位
    • res |= (n & 1):取出 n 的最右一位,加到結果上
    • n >>= 1:n 右移一位
  • 返回結果:
    • 返回 res

位運算符說明
#

  • <<=:左移賦值運算符,將左邊的數左移指定位數
  • |=:按位或賦值運算符,將左邊的數與右邊的數進行按位或運算
  • &:按位與運算符,取出最右邊的位
  • >>=:右移賦值運算符,將左邊的數右移指定位數

例子說明
#

n = 10100111

Stepn(原數)n & 1result(左移 + 加上)result(二進位)
110100111100000000 → 0000000100000000 → 00000001
201010011100000010 → 0000001100000010 → 00000011
300101001100000110 → 0000011100000110 → 00000111
400010100000001110 → 0000111000001110
500001010000011100 → 0001110000011100
600000101100111000 → 0011100100111001
700000010001110010 → 0111001001110010
800000001111100100 → 1110010111100101 ✅

最終 result = 11100101(8 位反轉後的結果)

完整程式碼
#

java
class Solution {
    public int reverseBits(int n) {
        // 初始化結果變數
        int res = 0;

        // 遍歷 32 位,逐位進行反轉
        for (int i = 0; i < 32; i++) {
            // 先把結果左移一位,空出最後一位
            res <<= 1;
            // 取出 n 的最右一位,加到結果上
            res |= (n & 1);
            // 將 n 右移,準備下一輪
            n >>= 1;
        }
        // 返回反轉後的結果
        return res;
    }
}

時間複雜度
#

  • 時間複雜度O(1),固定遍歷 32 次,與輸入大小無關
  • 空間複雜度O(1),只使用了常數個變數

相關文章

leetcode 191 - Number of 1 Bits
類別 
Leetcode
標籤 
Java Leetcode Easy Bit Problem Blind75
leetcode 338 - Counting Bits
類別 
Leetcode
標籤 
Java Leetcode Easy Bit Problem Blind75
leetcode 100 - Same Tree
類別 
Leetcode
標籤 
Java Leetcode Easy Tree Problem Blind75