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

LeetCode 342: Power of Four

·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-23

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

解題思路
#

4 的次方是 2 的次方,而且唯一的 1 在第 0、2、4… 位(Bit Manipulation)。0x55555555 的二進位是 0101...01,剛好是所有偶數位,所以 n & 0x55555555 != 0。另一種判斷:4^k = (3 + 1)^k ≡ 1 (mod 3),而 2 × 4^k ≡ 2 (mod 3)。

我的嘗試
#

一次 AC,當時就是 n > 0 and n & (n - 1) == 0 and n % 3 == 1,用的是 mod 3 的判斷。

正確解法
#

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

複雜度
#

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

要特別避免的錯誤
#

  • 只檢查 2 的次方不夠,2、8 不是 4 的次方。

面試口說整理
#

4 的次方一定是 2 的次方,而且那個 1 在偶數位,所以我先用 n & (n - 1) 檢查只有一個 1,再跟 0x55555555 做 AND 確認位置。時間 O(1)。

相關文章

LeetCode 231: Power of Two
·1 分鐘
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 解題筆記:2 的次方只有一個位元是 1,n & (n - 1) 會把最低的 1 消掉,結果是 0 就是;n 要是正數
LeetCode 405: Convert a Number to Hexadecimal
·1 分鐘
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 解題筆記:負數先加上 2^32 變成補數,再每次取 4 個位元(% 16)轉成十六進位;0 要特別處理
LeetCode 67: Add Binary
·1 分鐘
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 解題筆記:從兩個字串的尾巴往前逐位相加,進位是 sum // 2,這一位是 sum % 2
LeetCode 326: Power of Three
·1 分鐘
LeetCode Easy Math Recursion
LeetCode 326 解題筆記:一直除以 3 直到除不盡,剩 1 就是;不用迴圈的話,3^19 能被 n 整除就是
LeetCode 268: Missing Number
·1 分鐘
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 解題筆記:0 到 n 的總和減掉陣列總和就是缺的那個;缺的可能是 0
LeetCode 367: Valid Perfect Square
·1 分鐘
LeetCode Easy Math Binary-Search
LeetCode 367 解題筆記:在 [1, num] 上二分找 mid² == num,不用 sqrt