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

LeetCode 693: Binary Number with Alternating Bits

·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-08-30

  • 提交紀錄:Wrong Answer → Accepted ×4

解題思路
#

字串寫法:bin(n) 裡不能有 "00" 也不能有 "11"。位元寫法(Bit Manipulation):相鄰位元都不同時,x = n ^ (n >> 1) 的每一位都是 1,再用 x & (x + 1) == 0 檢查全部是 1。

我的嘗試
#

第一版寫成 '00' in s or '11' in s,意思剛好相反:2(10)回傳 False。改成 not in ... and not in 就 AC 了。

正確解法
#

class Solution:
    def hasAlternatingBits(self, n: int) -> bool:
        x = n ^ (n >> 1)
        return x & (x + 1) == 0

複雜度
#

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

要特別避免的錯誤
#

  • 條件是沒有 00 而且沒有 11,不要寫成有。

面試口說整理
#

相鄰位元都不同時,n 和 n 右移一位做 XOR 會得到全部是 1 的數,我再用 x & (x + 1) 是 0 檢查全部是 1。時間 O(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 起來,成對的抵消,剩下的就是多的那個
LeetCode 405: Convert a Number to Hexadecimal
·1 分鐘
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 解題筆記:負數先加上 2^32 變成補數,再每次取 4 個位元(% 16)轉成十六進位;0 要特別處理
LeetCode 231: Power of Two
·1 分鐘
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 解題筆記:2 的次方只有一個位元是 1,n & (n - 1) 會把最低的 1 消掉,結果是 0 就是;n 要是正數