【Lintcode】1046. Prime Number of Set Bits in Binary Representation

题目地址:

https://www.lintcode.com/problem/prime-number-of-set-bits-in-binary-representation/description

某个数二进制表示中 1 1 1的个数称为其“计算置位”。返回区间 [ L , R ] [L,R] [L,R]中的计算置位是素数的数的个数。其中 L ≤ R L\le R LR

计算计算置位可以用lowbit来做。而计算置位的范围无非就是 0 ∼ 32 0\sim 32 032,预处理一下即可。代码如下:

public class Solution {
    /**
     * @param L: an integer
     * @param R: an integer
     * @return: the count of numbers in the range [L, R] having a prime number of set bits in their binary representation
     */
    public int countPrimeSetBits(int L, int R) {
        // write your code here
        // 预处理素数判断,check[i]表示i是否是素数
        boolean[] check = {false,
                false, true, true, false, true,
                false, true, false, false, false,
                true, false, true, false, false,
                false, true, false, true, false,
                false, false, true, false, false,
                false, false, false, true, false,
                true, false};
    
        int res = 0;
        for (int i = L; i <= R; i++) {
            if (check[cal(i)]) {
                res++;
            }
        }
        
        return res;
    }
    
    // 算n的计算置位
    private int cal(int n) {
        int res = 0;
        while (n > 0) {
            n -= lowbit(n);
            res++;
        }
        
        return res;
    }
    
    private int lowbit(int x) {
        return x & -x;
    }
}

时间复杂度 O ( R − L ) O(R-L) O(RL),空间 O ( 1 ) O(1) O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值