原题网址:https://leetcode.com/problems/power-of-two/
Given an integer, write a function to determine if it is a power of two.
思路:数字n是2的整数次幂,当且仅当n的二进制表示有且只有一个1。
方法一:直接统计1比特数。
public class Solution {
public boolean isPowerOfTwo(int n) {
int count = 0;
for(;n>0 && count<=1; count += (n&1), n>>=1);
return count == 1;
}
}
方法二:直接获取最低位1比特。
public class Solution {
public boolean isPowerOfTwo(int n) {
return n>0 && n == (n & -n);
}
}