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
思路
看到簡單題,就for循環解決,然後發現超時,之後在討論中看到位運算,感覺就是一道數學題
代碼
class Solution {
public boolean isPowerOfTwo(int n) {
if (n < 1) {
return false;
}
for (int i = 1; i <= n; i = i * 2) {
if (i == n) {
return true;
}
}
return false;
}
}
位運算解法
數字 nn 若是 22 的次方,則一定滿足以下條件:
n & (n - 1)一定等於 00 ,因爲:
- 二進制下, nn 最高位爲 11 ,其餘所有位爲 00 ;
- 二進制下, n - 1n−1 最高位爲 00 ,其餘所有位爲 11;
一定有 n > 0n>0 。
因此,判斷n > 0且n & (n - 1) == 0則可確定 nn 是否是 2的次方
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}