762. Prime Number of Set Bits in Binary Representation
</> Solution
/**
* Problem: LeetCode 762 - Prime Number of Set Bits in Binary Representation
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int countPrimeSetBits(int left, int right) {
// Bitmask representing prime bit counts up to 19:
// Primes <= 19 are 2, 3, 5, 7, 11, 13, 17, 19
// mask = (1<<2)|(1<<3)|(1<<5)|(1<<7)|(1<<11)|(1<<13)|(1<<17)|(1<<19) = 665772
int primeMask = 665772;
int count = 0;
for (int i = left; i <= right; i++) {
int setBits = Integer.bitCount(i);
if (((primeMask >> setBits) & 1) != 0) {
count++;
}
}
return count;
}
}
"""
Problem: LeetCode 762 - Prime Number of Set Bits in Binary Representation
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
class Solution:
def countPrimeSetBits(self, left: int, right: int) -> int:
# Primes <= 19: 2, 3, 5, 7, 11, 13, 17, 19
prime_mask = 665772
count = 0
for num in range(left, right + 1):
set_bits = num.bit_count()
if (prime_mask >> set_bits) & 1:
count += 1
return count
/**
* Problem: LeetCode 762 - Prime Number of Set Bits in Binary Representation
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <algorithm>
class Solution {
public:
int countPrimeSetBits(int left, int right) {
// Primes <= 19: 2, 3, 5, 7, 11, 13, 17, 19
const int primeMask = 665772;
int count = 0;
for (int i = left; i <= right; i++) {
int setBits = __builtin_popcount(i);
if ((primeMask >> setBits) & 1) {
count++;
}
}
return count;
}
};
/**
* Problem: LeetCode 762 - Prime Number of Set Bits in Binary Representation
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {number} left
* @param {number} right
* @return {number}
*/
var countPrimeSetBits = function(left, right) {
const primeMask = 665772;
let count = 0;
for (let i = left; i <= right; i++) {
let n = i;
let setBits = 0;
while (n > 0) {
n &= (n - 1);
setBits++;
}
if ((primeMask >> setBits) & 1) {
count++;
}
}
return count;
};