【Description:】231. Power of Two Easy
Given an integer, write a function to determine if it is a power of two.
给定一个整型数,判断是否是2的倍数。
Example 1:
-
Input: 1
Output: true
Explanation: 20 = 1
Example 2: -
Input: 16
Output: true
Explanation: 24 = 16
Example 3: -
Input: 218
Output: false
因为在上篇文章中有关于计算整型数中有多少个1的实现。
计算无符号整型数n中有多少个1
所以在这实现也简单:
思路:
只需要判断整型数n是否只包含1个1.
public static boolean isPowerOfTwo(int n) {
if(n < 0){
return false;
}
int count = 0;
for(int i = 0; i < 32; i++){
if((n & 1) == 1){
count++;
}
if(count >1){
return false;
}
n = n>>>1;
}
if(count ==1) {
return true;
}
else{
return false;
}
}
网上高票回答:
public static boolean isPowerOfTwo2(int n) {
return n>0 && Integer.bitCount(n) == 1;
}
只想加一点说明:
最后i & 0x3f;得到的结果为:
i=∑i=031bi
为什么:选择0x3f
16进制 | 2进制 | 10进制 |
---|---|---|
0x3f | 00111111 | 63 |
因为32位的int所有的1加起来可能会到32,所以要用0x3f 去截取n的值。
参考:
https://blog.csdn.net/zhouzipeng000/article/details/56676885