[leetcode]231.Power of Two
阿新 • • 發佈:2018-10-14
amp 其余 bool 其它 說明 write solution clas 題目
題目
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);
}
}
[leetcode]231.Power of Two