↓快轉到主要內容
  1. LeetCode/

LeetCode 868: Binary Gap

·1 分鐘· ·
LeetCode Easy Bit-Manipulation
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-09-17

  • 提交紀錄:Runtime Error ×2 → Wrong Answer ×5 → Accepted

解題思路
#

從最低位往上掃(Bit Manipulation),記錄上一個 1 的位置 last,遇到新的 1 時距離是 i - last,取最大值。只有一個 1 時答案是 0。

我的嘗試
#

前幾版用 s.split('1') 找最長的一串 0 再加 1:

  • 結尾的 0 也被算進去,但它們後面沒有 1:24(11000)回傳 4,答案 1。
  • 用 strip('0') 去掉結尾之後,相鄰的 1 距離是 1,但切出來的空字串長度是 0:7(111)回傳 0,5(101)也一直差一。

改成記錄 1 的位置才 AC。

正確解法
#

class Solution:
    def binaryGap(self, n: int) -> int:
        last, best, i = -1, 0, 0
        while n:
            if n & 1:
                if last >= 0:
                    best = max(best, i - last)
                last = i
            n >>= 1
            i += 1
        return best

複雜度
#

時間 O(log n),空間 O(1)。

要特別避免的錯誤
#

  • 距離是兩個 1 的位置差,相鄰的 1 距離是 1,不是 0。
  • 結尾的 0 後面沒有 1,不算間隔。

面試口說整理
#

我從最低位往上掃,記錄上一個 1 的位置,每遇到新的 1 就用位置差更新最大值。時間 O(log n)、空間 O(1)。

相關文章

LeetCode 832: Flipping an Image
·1 分鐘
LeetCode Easy Array Two-Pointers Bit-Manipulation Matrix
LeetCode 832 解題筆記:每一列先左右反轉再把 0、1 互換;可以用左右指針同時做
LeetCode 693: Binary Number with Alternating Bits
·1 分鐘
LeetCode Easy Bit-Manipulation
LeetCode 693 解題筆記:相鄰位元都不同,代表二進位字串裡沒有 00 也沒有 11;位元版本是 n ^ (n » 1) 全部是 1
LeetCode 645: Set Mismatch
·1 分鐘
LeetCode Easy Array Hash-Table Bit-Manipulation Sorting
LeetCode 645 解題筆記:用總和算:missing = 1..n 的和 - set 的和,duplicate = 陣列總和 - set 的和
LeetCode 476: Number Complement
·1 分鐘
LeetCode Easy Bit-Manipulation
LeetCode 476 解題筆記:做一個跟 num 一樣長、全部是 1 的遮罩,num ^ mask 就是補數
LeetCode 342: Power of Four
·1 分鐘
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 解題筆記:先確認是 2 的次方,再確認那個 1 在偶數位:n & 0x55555555 != 0,或 n % 3 == 1
LeetCode 389: Find the Difference
·1 分鐘
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 解題筆記:t 比 s 多一個字元,把兩個字串的所有字元 XOR 起來,成對的抵消,剩下的就是多的那個