加载中...
762-二进制表示中质数个计算置位(Prime Number of Set Bits in Binary Representation)
发表于:2021-12-03 | 分类: 简单
字数统计: 776 | 阅读时长: 3分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/prime-number-of-set-bits-in-binary-representation

英文原文

Given two integers left and right, return the count of numbers in the inclusive range [left, right] 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 1's present when written in binary.

  • For example, 21 written in binary is 10101, which has 3 set bits.

 

Example 1:

Input: left = 6, right = 10
Output: 4
Explanation:
6  -> 110 (2 set bits, 2 is prime)
7  -> 111 (3 set bits, 3 is prime)
8  -> 1000 (1 set bit, 1 is not prime)
9  -> 1001 (2 set bits, 2 is prime)
10 -> 1010 (2 set bits, 2 is prime)
4 numbers have a prime number of set bits.

Example 2:

Input: left = 10, right = 15
Output: 5
Explanation:
10 -> 1010 (2 set bits, 2 is prime)
11 -> 1011 (3 set bits, 3 is prime)
12 -> 1100 (2 set bits, 2 is prime)
13 -> 1101 (3 set bits, 3 is prime)
14 -> 1110 (3 set bits, 3 is prime)
15 -> 1111 (4 set bits, 4 is not prime)
5 numbers have a prime number of set bits.

 

Constraints:

  • 1 <= left <= right <= 106
  • 0 <= right - left <= 104

中文题目

给定两个整数 L 和 R ,找到闭区间 [L, R] 范围内,计算置位位数为质数的整数个数。

(注意,计算置位代表二进制表示中1的个数。例如 21 的二进制表示 10101 有 3 个计算置位。还有,1 不是质数。)

示例 1:

输入: L = 6, R = 10
输出: 4
解释:
6 -> 110 (2 个计算置位,2 是质数)
7 -> 111 (3 个计算置位,3 是质数)
9 -> 1001 (2 个计算置位,2 是质数)
10-> 1010 (2 个计算置位,2 是质数)

示例 2:

输入: L = 10, R = 15
输出: 5
解释:
10 -> 1010 (2 个计算置位, 2 是质数)
11 -> 1011 (3 个计算置位, 3 是质数)
12 -> 1100 (2 个计算置位, 2 是质数)
13 -> 1101 (3 个计算置位, 3 是质数)
14 -> 1110 (3 个计算置位, 3 是质数)
15 -> 1111 (4 个计算置位, 4 不是质数)

注意:

  1. L, R 是 L <= R 且在 [1, 10^6] 中的整数。
  2. R - L 的最大值为 10000。

通过代码

官方题解

方法一:

算法:

LR,我们首先计算该数字转换为二进制有多少个 1。如果数量是 2, 3, 5, 7, 11, 13, 17, 19,则我们增加计数。最高是 19 的原因是 $R \leq 10^6 < 2^{20}$。

[solution1-Python]
class Solution(object): def countPrimeSetBits(self, L, R): primes = {2, 3, 5, 7, 11, 13, 17, 19} return sum(bin(x).count('1') in primes for x in xrange(L, R+1))
[solution1-Java]
class Solution { public int countPrimeSetBits(int L, int R) { int ans = 0; for (int x = L; x <= R; ++x) if (isSmallPrime(Integer.bitCount(x))) ans++; return ans; } public boolean isSmallPrime(int x) { return (x == 2 || x == 3 || x == 5 || x == 7 || x == 11 || x == 13 || x == 17 || x == 19); } }

复杂度分析

  • 时间复杂度:$O(D)$,其中 $D = R-L$,指的是所需判断数字的个数。
  • 空间复杂度:$O(1)$。

统计信息

通过次数 提交次数 AC比率
18552 26459 70.1%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言

相似题目

题目 难度
位1的个数 简单
上一篇:
430-扁平化多级双向链表(Flatten a Multilevel Doubly Linked List)
下一篇:
763-划分字母区间(Partition Labels)
本文目录
本文目录