Leetcode Note: Go - Prime Number of Set Bits in Binary Representation

Prime Number of Set Bits in Binary Representation - LeetCode
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/

  • Go 言語で取り組んだメモ

所感

  • left, right の数値が渡されるので、その間でビット表現した際の素数となる数値をカウントして return する

回答

Prime Number of Set Bits in Binary Representation - LeetCode
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/solution/

Golang Solution - LeetCode Discuss
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/1117586/Golang-Solution

func countPrimeSetBits(L int, R int) int {
    	mp := make(map[int]bool)
	val := []int{2,3,5,7,11,13,17,19}
	
	for _, v := range val {
		mp[v] = true
	}
	
	cnt := 0
	for i:= L; i <= R; i++ {
		bits := 0
		for n := i; n > 0; n >>= 1 {
			bits += n &1
		}
		if _, ok := mp[bits]; ok {
			cnt++
		} 
	}
	
	return cnt
}