762. 二進位制表示中質數個計算置位
阿新 • • 發佈:2020-08-23
762. 二進位制表示中質數個計算置位
給定兩個整數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 是質數)
12 -> 1100 (2 個計算置位, 2 是質數)
13 -> 1101 (3 個計算置位, 3 是質數)
14 -> 1110 (3 個計算置位, 3 是質數)
15 -> 1111 (4 個計算置位, 4 不是質數)
程式碼
#include<iostream> #include<bits/stdc++.h> #include<cstring> #include<vector> using namespace std; int getCount(int n){int count=0; while(n>0){ n=n&(n-1); count++; } return count; } int isPrime(int n){ if (n==1) return 0; if(n==2) return 1; for (int i = 2; i <= sqrt(n); i++) { if (n%i==0) { return 0; } } return 1; }int main(){ int L,R,count=0; cin>>L>>R; for (int i = L; i <= R; i++) { if(isPrime(getCount(i)))count++; } cout<<count<<endl; }
方法一:
演算法:
從 L 到 R,我們首先計算該數字轉換為二進位制有多少個 1。如果數量是 2, 3, 5, 7, 11, 13, 17, 19,則我們增加計數。最高是 19 的原因是
R≤106<220。
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); } }