Prime Number of Set Bits in Binary Representation — LeetCode 762 Python Solution
- Problem
- #762
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation. Recall that the number of set bits an integer has is the number of 1's present when written in binary.
Example
- Input
- left = 6, right = 10
- Output
- 4
- Explanation
- 6 -> 110 (2 set bits, 2 is prime)
Python solution
class Solution:
def countPrimeSetBits(self, left: int, right: int) -> int:
primes = {2, 3, 5, 7, 11, 13, 17, 19}
return sum(i.bit_count() in primes for i in range(left, right + 1))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 762. Prime Number of Set Bits in Binary Representation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 762. Prime Number of Set Bits in Binary Representation?
- LeetCode 762. Prime Number of Set Bits in Binary Representation is rated Easy on LeetCode.
- What is the time complexity of LeetCode 762. Prime Number of Set Bits in Binary Representation?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 762. Prime Number of Set Bits in Binary Representation?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 762. Prime Number of Set Bits in Binary Representation cover?
- LeetCode 762. Prime Number of Set Bits in Binary Representation is tagged Bit Manipulation and Math on LeetCode.