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

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容