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

LeetCode 231: Power of Two

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

基本資料
#

難易度: easy 第一次嘗試:2022-08-22

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

解題思路
#

n & (n - 1) 會把最低位的 1 變成 0(Bit Manipulation)。2 的次方只有一個 1,消掉之後就是 0。0 和負數不是 2 的次方,要先排除。

我的嘗試
#

  • 第一版寫成 (n > 0) & (n & (n - 1)) == 0,& 比 == 先算,n = 0 時變成 (False & 0) == 0,回傳 True。
  • 下一版拿掉 == 0,意思變成「n & (n - 1) 不是 0」,剛好相反:4 回傳 0。2022-11 重寫時又寫了一次 n > 0 and n & (n - 1),加上 not 才 AC。

正確解法
#

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

複雜度
#

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

要特別避免的錯誤
#

  • Python 的 & 比 == 先算:(n > 0) & (n & (n - 1)) == 0 會變成 ((n > 0) & (n & (n - 1))) == 0。用 and 連接兩個條件。
  • n & (n - 1) 是 0 才是 2 的次方,不要寫反。

面試口說整理
#

2 的次方只有一個位元是 1,n & (n - 1) 會消掉最低位的 1,所以我檢查 n 是正數而且 n & (n - 1) 是 0。時間 O(1)。

相關文章

LeetCode 67: Add Binary
·1 分鐘
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 解題筆記:從兩個字串的尾巴往前逐位相加,進位是 sum // 2,這一位是 sum % 2
LeetCode 234: Palindrome Linked List
·1 分鐘
LeetCode Easy Linked-List Two-Pointers Stack Recursion
LeetCode 234 解題筆記:快慢指針找中點,反轉後半段,再從兩端往中間比;O(1) 額外空間
LeetCode 258: Add Digits
·1 分鐘
LeetCode Easy Math Simulation Number-Theory
LeetCode 258 解題筆記:反覆把位數相加直到剩一位;O(1) 解法是 digital root:1 + (n - 1) % 9
LeetCode 171: Excel Sheet Column Number
·1 分鐘
LeetCode Easy Math String
LeetCode 171 解題筆記:從左到右 res = res × 26 + 字母的值(A = 1)
LeetCode 202: Happy Number
·1 分鐘
LeetCode Easy Hash-Table Math Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 202 解題筆記:一直取位數平方和,會走到 1 或進入環;用集合記看過的數,或用快慢指針判圈
LeetCode 203: Remove Linked List Elements
·1 分鐘
LeetCode Easy Linked-List Recursion
LeetCode 203 解題筆記:頭節點也可能要刪,用 dummy head 讓每次刪除都變成刪 cur.next;刪完不要前進