Counting Prime Set Bits in Binary Representation

🚀 Coding Practice — Prime Number of Set Bits (Bit Manipulation) Today I solved an interesting bit manipulation problem: 👉 Given two integers left and right, count how many numbers in the range [left, right] have a prime number of set bits in their binary representation. 🧠 Problem Understanding A set bit means a 1 in binary representation. Example: 21 → 10101 → 3 set bits We must: Convert each number in range [left, right] to binary Count number of 1s Check if that count is prime Return total count 🔍 Key Insight (Optimization Trick) Given constraint: 1 ≤ left ≤ right ≤ 10^6 0 ≤ right - left ≤ 10^4 Maximum number of bits required for 10^6: log₂(10^6) ≈ 20 So maximum possible set bits = 20 That means we only need to check primes up to 20: {2, 3, 5, 7, 11, 13, 17, 19} ⚡ Instead of checking prime every time, we store these in a set for O(1) lookup. ✅ Optimized Python Solution class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: # Prime numbers up to 20 (maximum possible set bits) primes = {2, 3, 5, 7, 11, 13, 17, 19} count = 0 for num in range(left, right + 1): set_bits = num.bit_count() # Fast built-in method if set_bits in primes: count += 1 return count 🔎 Example 1 Input: left = 6, right = 10 NumberBinarySet BitsPrime?61102✅71113✅810001❌910012✅1010102✅ ✔ Output = 4 ⏱ Complexity Analysis Time Complexity: O(N) where N = right - left (max 10^4) Space Complexity: O(1) Very efficient and well within constraints. #Python #CodingPractice #BitManipulation #ProblemSolving #DataStructures #InterviewPreparation #LeetCode

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories