LeetCode-Power of Two
阿新 • • 發佈:2018-12-16
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;
}
}