Difficulty: Easy

Related Topics: Bit Manipulation

Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) 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 1s present when written in binary. For example, 21 written in binary is 10101 which has 3 set bits. Also, 1 is not a prime.)

Example 1:

  1. Input: L = 6, R = 10
  2. Output: 4
  3. Explanation:
  4. 6 -> 110 (2 set bits, 2 is prime)
  5. 7 -> 111 (3 set bits, 3 is prime)
  6. 9 -> 1001 (2 set bits , 2 is prime)
  7. 10->1010 (2 set bits , 2 is prime)

Example 2:

  1. Input: L = 10, R = 15
  2. Output: 5
  3. Explanation:
  4. 10 -> 1010 (2 set bits, 2 is prime)
  5. 11 -> 1011 (3 set bits, 3 is prime)
  6. 12 -> 1100 (2 set bits, 2 is prime)
  7. 13 -> 1101 (3 set bits, 3 is prime)
  8. 14 -> 1110 (3 set bits, 3 is prime)
  9. 15 -> 1111 (4 set bits, 4 is not prime)

Note:

  1. L, R will be integers L <= R in the range [1, 10^6].
  2. R - L will be at most 10000.

Solution

Language: Java

  1. class Solution {
  2. // 665772 (10100010100010101100)
  3. // 通过在 2th, 3th ... 的 bit 位上设置为 1
  4. // 在通过右移运算来把这个 1 取出来
  5. public int countPrimeSetBits(int L, int R) {
  6. int ans = 0;
  7. for (int i = L; i <= R; i++) {
  8. ans += 665772 >> Integer.bitCount(i) & 1;
  9. }
  10. return ans;
  11. }
  12. }
  13. class Solution {
  14. public int countPrimeSetBits(int L, int R) {
  15. int ans = 0;
  16. for (int i = L; i <= R; i++) {
  17. if (isSmallPrime(Integer.bitCount(i))) {
  18. ans++;
  19. }
  20. }
  21. return ans;
  22. }
  23. private boolean isSmallPrime(int a) {
  24. return a == 2 || a == 3 || a == 5 || a == 7 ||
  25. a == 11 || a == 13 || a == 17 || a == 19;
  26. }
  27. }