leetcode (go Language) binary representation prime number set is calculated

Given two integers L and R, to find the closed interval [L, R & lt] within the range, counting the number of bits set to the integer prime number.
(Note that the calculation indicates the number set representing a binary 1, for example, in a binary representation of 21 is 3 10101 set there is calculated, not a prime number...)
Example 1:
Input: L = 6, R = 10
Output: 4
explains:
6 -> 110 (2 calculated is set, 2 is a prime number)
7 -> 111 (3 calculated is set, 3 is a prime number)
9 -> 1001 (2 calculated is set, 2 is a prime number)
10- > 1010 (2 calculated is set, 2 is a prime number)
example 2:
input: L = 10, R = 15
output: 5
explanation:
10 -> 1010 (2 calculated is set, 2 is a prime number)
11--> 1011 ( 3 is calculated is set, 3 is a prime number)
12--> 1100 (2 calculated is set, 2 is a prime number)
13--> 1101 (3 calculated is set, 3 is a prime number)
14--> 1110 (3 calculated set 3 is a prime number)
15--> 1111 (4 set computing, not a prime number 4)
Note:
L, R & lt is L <= R and is an integer in [1, 10 ^ 6].
R - the maximum value of L is 10000.

func bin(num int) int {
    count := 0
    for num != 0 {
        count += 1
        num &= num-1
    }
    return count
}


func countPrimeSetBits(L int, R int) int {
    st := make(map[int]bool)
    arrs := make([]int,0)
    arrs = append(arrs, 2, 3, 5, 7, 11, 13, 17, 19)
    for _,value := range arrs {
        st[value] = true
    }

    ret := 0
    for i:=L;i<R+1;i++ {
        count := bin(i)
        ok := st[count]

        if ok == true {
            ret += 1
        }
    }

    return ret

}

The following program output,

8982195-472827661f4789e4.png
image.png

Guess you like

Origin blog.csdn.net/weixin_34092370/article/details/91031561