标签:code OLE == isp func 题目 个数 一个 leetcode
Given an integer, write a function to determine if it is a power of two.
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的个数,如果只有一个1,说明其为2的幂。
class Solution {
public boolean isPowerOfTwo(int n) {
if(n < 0) return false;
int res = 0;
for(int i = 0; i < 32; i++) {
res += (n&1);
n >>= 1;
}
return res == 1;
}
}
如果一个数是2的次方数的话,根据上面分析,那么它的二进数必然是最高位为1,其它都为0,那么如果此时我们减1的话,则最高位会降一位,其余为0的位现在都为变为1,那么我们把两数相与,就会得到0,用这个性质也能来解题,而且只需一行代码就可以搞定。
class Solution {
public boolean isPowerOfTwo(int n) {
return ((n & (n-1))==0 && n>0);
}
}
标签:code OLE == isp func 题目 个数 一个 leetcode
原文地址:https://www.cnblogs.com/shinjia/p/9785645.html