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

LeetCode 3950: Exactly One Consecutive Set Bits Pair

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

基本資料
#

難易度: easy 第一次嘗試:2026-06-11

  • 提交紀錄:Accepted(一次通過)

解題思路
#

n >> 1 把每一位往右移一格,跟 n 做 AND 之後,第 i 位是 1 代表 n 的第 i 和 i + 1 位都是 1(Bit Manipulation 模板二)。所以 pairs = n & (n >> 1) 的 1 的個數就是相鄰配對數;剛好一對就是 pairs 不是 0 而且只有一個 1。重疊的也算,例如 111 有兩對。

我的解法
#

class Solution:
    def consecutiveSetBits(self, n: int) -> bool:
        pairs = n & (n >> 1)
        return pairs != 0 and pairs & (pairs - 1) == 0

我當時把 bin(n) 轉成字串,數 "11" 出現幾次(逐位比對,重疊的也會數到)。

複雜度
#

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

要特別避免的錯誤
#

  • str.count("11") 不會數重疊的,"111".count("11") 是 1;要逐位比對或用位元運算。

面試口說整理
#

n & (n >> 1) 的每個 1 代表一對相鄰的 1,所以我檢查它不是 0、而且 x & (x - 1) 是 0,也就是剛好一個 1。時間 O(1)。

相關文章

LeetCode 3827: Count Monobit Integers
·1 分鐘
LeetCode Easy Bit-Manipulation Enumeration
LeetCode 3827 解題筆記:每一位都一樣的數只有 0 和 2^k - 1;個數就是 (n + 1).bit_length()
LeetCode 1763: Longest Nice Substring
·1 分鐘
LeetCode Easy Sliding-Window Divide-and-Conquer Hash-Table String Bit-Manipulation
LeetCode 1763 解題筆記:沒有大小寫配對的字元一定不在答案裡,用它切開字串遞迴;長度相同時取左邊的
LeetCode 3750: Minimum Number of Flips to Reverse Binary String
·1 分鐘
LeetCode Easy Two-Pointers Bit-Manipulation String
LeetCode 3750 解題筆記:把二進位字串跟它的反轉逐位比較,不同的位數就是答案
LeetCode 3688: Bitwise OR of Even Numbers in an Array
·1 分鐘
LeetCode Easy Bit-Manipulation Array Simulation
LeetCode 3688 解題筆記:只對偶數做 OR;初始值 0 剛好也是「沒有偶數」時的答案
LeetCode 2859: Sum of Values at Indices With K Set Bits
·1 分鐘
LeetCode Easy Array Bit-Manipulation
LeetCode 2859 解題筆記:看的是 index 的二進位有幾個 1,不是值
LeetCode 762: Prime Number of Set Bits in Binary Representation
·1 分鐘
LeetCode Easy Math Bit-Manipulation Primality-Test
LeetCode 762 解題筆記:數字最多 10^6 < 2^20,1 的個數最多 19,直接比對小質數集合