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的阶乘,我的思路是一直整除即可,但要注意最后得到1的也是可以整除的。Accepted代码如下:
class Solution {
public boolean isPowerOfTwo(int n) {
if (n <= 0) {
return false;
} else if (n == 1) {
return true;
} else {
while (n > 1) {
if (n % 2 == 1) {
return false;
} else {
n /= 2;
}
}
}
return true;
}
}