美文网首页
LeetCode之Prime Number of Set Bit

LeetCode之Prime Number of Set Bit

作者: 糕冷羊 | 来源:发表于2019-01-01 00:07 被阅读0次

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

    相关文章

      网友评论

          本文标题:LeetCode之Prime Number of Set Bit

          本文链接:https://www.haomeiwen.com/subject/lvuglqtx.html