题目描述:https://leetcode-cn.com/problems/power-of-two/description/
思路:
很简单的一道题,按照迭代的思路,可以这样写:
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
# return n != 0 and n == n&(-n)
if n <= 0:
return False
while n != 1:
if n%2 != 0:
return False
else:
n = n/2
return True
上述思路是按照迭代完成的,也可以使用位运算。二的幂在二进制中有这样一种特点:只有一位是0,其余位均为1。
2 n 2^{n} 2n的补码与它自身的与运算结果是其本身。以2为例,2的二进制表示为0010,-2的二进制表示为2的补码1110, 2&-2的结果为0010。
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n != 0 and n == n&(-n)
2 n 2^{n} 2n与 2 n − 1 2^{n}-1 2n−1的与运算结果为0。
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n != 0 and not n&(n-1)