問題: 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.git
(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.)github
方法: 從L遍歷到R,統計數字的1bit位數,對1bit位數和進行質數判斷。若是爲質數則計數加1,最後輸出計數值。包含兩個私有方法:1. 獲取1bit位個數,2. 判斷數字是否爲質數。bash
具體實現:ui
class PrimeNumberOfSetBitsInBinaryRepresentation {
fun countPrimeSetBits(L: Int, R: Int): Int {
var count = 0
for (i in L..R) {
if (isPrimeNum(getBits(i))) {
count++
}
}
return count
}
private fun getBits(num: Int): Int {
var cacheNum = num
var bits = 0
while (cacheNum != 0) {
if (cacheNum % 2 == 1) {
bits++
}
cacheNum /= 2
}
return bits
}
private fun isPrimeNum(num: Int): Boolean {
if (num == 1) {
return false
} else {
for (i in 2 until num) {
if (num % i == 0) {
return false
}
}
return true
}
}
}
fun main(args: Array<String>) {
val primeNumberOfSetBitsInBinaryRepresentation = PrimeNumberOfSetBitsInBinaryRepresentation()
val result = primeNumberOfSetBitsInBinaryRepresentation.countPrimeSetBits(990, 1048)
println("result: $result")
}
複製代碼
有問題隨時溝通spa
具體代碼實現能夠參考Githubcode