leetcode刷題筆記231 2的冪
阿新 • • 發佈:2018-04-30
show 判斷 clas 進制 OS 分析 分享 bsp gif
題目描述:
給定一個整數,寫一個函數來判斷它是否是2的冪。
題目分析:
判斷一個整數是不是2的冪,可根據二進制來分析。2的冪如2,4,8,等有一個特點:
二進制數首位為1,其他位為0,如2為10,4為100
2&(2-1)=0 4&(4-1)=0
即得出結論如果一個數n為2的冪,則n(n-1)=0
此題通過率37.6%,挺高的
解答代碼:
C++版:
class Solution { public: bool isPowerOfTwo(int n) { if (n<=0) return false;Codereturn ((n&(n-1))==0); } };
Python版:
class Solution: def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ if n<=0: return False return ((n & (n-1))==0)Code
leetcode刷題筆記231 2的冪