Skip to content

Latest commit

 

History

History
29 lines (24 loc) · 753 Bytes

762.-prime-number-of-set-bits-in-binary-representation.md

File metadata and controls

29 lines (24 loc) · 753 Bytes

762. Prime Number of Set Bits in Binary Representation

class Solution:
    def countPrimeSetBits(self, L: int, R: int) -> int:
        ## 位操作,1 出现的次数为prime
        ## 还是要熟悉输入的的边界,2 的 20 次方已经可以cover 所有input了
        ans = 0
        for i in range(L, R + 1):
            if self.isPrime(self.countOne(i)):
                ans += 1
        return ans
        
    ## 优化了这里 
    def isPrime(self, number):
        if number in {2, 3, 5, 7, 11, 13, 17, 19}:
            return True
        else:
            return False
        
    
    def countOne(self, num):
        ans = 0
        while num > 0:
            ans += 1
            num &= (num-1)
        return ans