LeetCode 762. Prime Number of Set Bits in Binary Representation
考点 | 难度 |
---|---|
Math | Easy |
题目
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.
思路
因为题目里的范围是1到十的六次方,所以二进制最多有20位。prime位置写成true,其他位置写成false,然后用helper function算一共有几个1。
答案
public boolean isPowerOfThree(int n) {
while(n>=3){
if(n%3!=0) return false;
n/=3;
}
return n==1;
}
}