EasyNo. 0762

Prime Number of Set Bits in Binary Representation — LeetCode 762 Python Solution

Topics
Bit Manipulation, Math
Reading time
2 min

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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0029Divide Two IntegersMedium
0067Add BinaryEasy
0231Power of TwoEasy
0342Power of FourEasy
0371Sum of Two IntegersMedium
0405Convert a Number to HexadecimalEasy

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.