LeetCode之Prime Number of Set Bits in Binary Representation(Kotlin)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wanglikun7342/article/details/79188693

问题:
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.)


方法:
从L遍历到R,统计数字的1bit位数,对1bit位数和进行质数判断。如果为质数则计数加1,最后输出计数值。包含两个私有方法:1. 获取1bit位个数,2. 判断数字是否为质数。

具体实现:

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")
}

有问题随时沟通

具体代码实现可以参考Github

猜你喜欢

转载自blog.csdn.net/wanglikun7342/article/details/79188693