2的幂 (leetcode 231)
一:解题思路
方法一:只要原始数字为2的倍数,不断的去除以2,直到最后结果为1.Time:O(log(n)),Space:O(1)
方法二:我们可以发现,当一个数中有且仅有某一位二进制为1的时候,那么这个数就肯定是2的幂。所以我们可以看n&(n-1)==0来判断这个数是否为2的幂。Time:O(1),Space:O(1)
二:完整代码示例 (C++版和Java版)
方法一C:
bool isPowerOfTwo(int n) { if (n <= 0) return false; while (n % 2 == 0) n /= 2; return n == 1; }
方法二C:
bool isPowerOfTwo(int n) { return n > 0 && ((n&n-1)==0); }
方法一C++:
class Solution { public: bool isPowerOfTwo(int n) { if (n <= 0) return false; while (n%2==0) { n /= 2; } return (n==1); } };
方法一Java:
class Solution { public boolean isPowerOfTwo(int n) { if(n<=0) return false; while(n%2==0) n/=2; return n==1; } }
方法二C++:
class Solution { public: bool isPowerOfTwo(int n) { return n > 0 && (n&(n - 1)) == 0; } };
方法二Java:
class Solution { public boolean isPowerOfTwo(int n) { return n>0 && (n&(n-1))==0; } }
方法一Python:
class Solution: def isPowerOfTwo(self, n: int) -> bool: if n<=0: return False while n%2==0: n/=2 return n==1
方法二Python:
class Solution: def isPowerOfTwo(self, n: int) -> bool: return n>0 and ((n&n-1)==0)

浙公网安备 33010602011771号