1. 程式人生 > 其它 >【Lintcode】1046. Prime Number of Set Bits in Binary Representation

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

技術標籤:# 二分、位運算與數學javaleetcode演算法資料結構

題目地址:

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)