↓Skip to main content
  1. LeetCode/

LeetCode 762: Prime Number of Set Bits in Binary Representation

·1 min· ·
LeetCode Easy Math Bit-Manipulation Primality-Test
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-06

  • Submissions: Accepted (first try)

Approach
#

With right <= 10^6 < 2^20, a set-bit count is at most 19, and the primes up to that are 2, 3, 5, 7, 11, 13, 17, 19. Count each number’s bits (Bit Manipulation) and test membership.

My Solution
#

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))

Complexity
#

Time O((right - left) · log right), space O(1).

Mistakes to Avoid
#

  • 1 is not prime.

Interview Explanation
#

Numbers in range have at most 20 bits, so the count is at most 19; I put the primes up to 19 in a set and check each number’s count. Time is the range length times the bit count.

Related

LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately
LeetCode 231: Power of Two
·2 mins
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 note: a power of two has exactly one set bit, and n & (n - 1) clears the lowest one, so the result is 0 exactly then; n must be positive
LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 507: Perfect Number
·1 min
LeetCode Easy Math
LeetCode 507 note: divisors come in pairs, so enumerate up to √n and add both d and n / d for each divisor found
LeetCode 461: Hamming Distance
·1 min
LeetCode Easy Bit-Manipulation
LeetCode 461 note: each 1 in x ^ y is a differing bit, so count the ones