Description:
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
题意:给定一个数,计算是否为2的幂次方;
解法:既然是计算是否为2的幂次方,那么首先可以排除掉小于1的那些整数;其次,我们便可以计算其二进制表示,除了高位为1以外,其他位应当都为0;
Java
class Solution {
public boolean isPowerOfTwo(int n) {
if (n < 1) return false;
while (n > 0) {
if (n == 1) return true;
if (n % 2 == 1) return false;
n /= 2;
}
return true;
}
}