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

LeetCode 762: Prime Number of Set Bits in Binary Representation

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

基本資料
#

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

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

解題思路
#

right <= 10^6 < 2^20,所以 1 的個數最多 19,質數只有 2, 3, 5, 7, 11, 13, 17, 19。逐一數 1 的個數(Bit Manipulation),看在不在這個集合裡。

我的解法
#

class Solution:
    def countPrimeSetBits(self, left: int, right: int) -> int:
        primes = {2, 3, 5, 7, 11, 13, 17, 19}
        return sum(bin(x).count("1") in primes for x in range(left, right + 1))

複雜度
#

時間 O((right - left) · log right),空間 O(1)。

要特別避免的錯誤
#

  • 1 不是質數。

面試口說整理
#

範圍內的數最多 20 位元,1 的個數最多 19,所以我把 19 以內的質數放進集合,逐一數 1 的個數檢查。時間是範圍長度乘上位元數。

相關文章

LeetCode 342: Power of Four
·1 分鐘
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 解題筆記:先確認是 2 的次方,再確認那個 1 在偶數位:n & 0x55555555 != 0,或 n % 3 == 1
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 要是正數
LeetCode 67: Add Binary
·1 分鐘
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 解題筆記:從兩個字串的尾巴往前逐位相加,進位是 sum // 2,這一位是 sum % 2
LeetCode 507: Perfect Number
·1 分鐘
LeetCode Easy Math
LeetCode 507 解題筆記:因數成對出現,只要枚舉到 √n,每找到 d 就同時加上 d 和 n / d
LeetCode 461: Hamming Distance
·1 分鐘
LeetCode Easy Bit-Manipulation
LeetCode 461 解題筆記:x ^ y 的每個 1 就是一個不同的位元,數 1 的個數