Sets bits for prime numbers in binary representation

2. The number of prime numbers in the binary representation is calculated and set

2.1, the title requirements

  Given two integers left and right, in the closed interval [left, right], count and return the number of integers whose bits are prime. Calculating the set bits is the number of 1's in the binary representation.

  For example, the binary representation of 21, 10101, has 3 computed bits set.

示例 1

输入:left = 6, right = 10
输出:4
解释:
6 -> 110 (2 个计算置位,2 是质数)
7 -> 111 (3 个计算置位,3 是质数)
9 -> 1001 (2 个计算置位,2 是质数)
10-> 1010 (2 个计算置位,2 是质数)
共计 4 个计算置位为质数的数字。
示例 2

输入:left = 10, right = 15
输出:5
解释:
10 -> 1010 (2 个计算置位, 2 是质数)
11 -> 1011 (3 个计算置位, 3 是质数)
12 -> 1100 (2 个计算置位, 2 是质数)
13 -> 1101 (3 个计算置位, 3 是质数)
14 -> 1110 (3 个计算置位, 3 是质数)
15 -> 1111 (4 个计算置位, 4 不是质数)
共计 5 个计算置位为质数的数字。


提示:

1 <= left <= right <= 106
0 <= right - left <= 104

Source: LeetCode
Link: https://leetcode-cn.com/problems/prime-number-of-set-bits-in-binary-representation

2.2, problem solving ideas

  In this question, I used Hamming weight to solve the problem. I used Hamming weight to calculate the number of digits in the interval, and then made further judgments by judging whether the number of digits was prime.

2.3. Algorithm

class Solution {
    
    
    public int countPrimeSetBits(int left, int right) {
    
    
        int res = 0;
        for(int i = left;i <= right;i++){
    
    
            //使用了汉明重量
            int hanmingweight = 0;
            int n = i;
            //计算置位位数
            while(n>0){
    
    
                //把数字转化为二进制,然后最后一位和1按位与,如果是1加1,如果是0加0
                hanmingweight += n&1;
                //右移一位,依次判断
                n >>= 1;
            }
            //判断置位位数是否为质数
            if(hanmingweight >= 2){
    
    
                //当汉明重量等于2、3、5、7或者不是2、3、5、7的倍数就是质数
                if(hanmingweight == 2||hanmingweight == 3||hanmingweight == 5||hanmingweight == 7){
    
    
                    res++;
                }else if(hanmingweight % 2 == 0||hanmingweight % 3 == 0||hanmingweight % 5 == 0||hanmingweight % 7 == 0){
    
    
                    continue;
                }else{
    
    
                    res++;
                }
            }
        }
        return res;
    }
}

Reference video: B station up master Hey Hei Ge

Guess you like

Origin blog.csdn.net/qq_52916408/article/details/123998712