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

本文介绍了一个算法,用于计算给定范围内整数的二进制表示中具有质数数量的1位数的数量。通过遍历指定范围内的每个整数,统计其二进制形式中的1位数,并判断该数量是否为质数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值