原问题链接: https://leetcode.com/problems/power-of-two/
Given an integer, write a function to determine if it is a power of two.
参考别人的回答如下:
这两个回答的基本思路是2的n次方在转换为二进制表示时只有一个1,所以将n用二进制表示并数一下转换后数字里1的个数就可以了。
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n <=0:
return False
#use bin() to convert n into binary number
return bin(n).count('1') == 1
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
counts = 0
if n>0:
while n!=0:
counts += n&1
#>> is bitwise operator
n>>=1
return counts==1
相关bitwise文档:
https://wiki.python.org/moin/BitwiseOperators
The Operators:
x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2y.
x >> y
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2y.
x & y
Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.
x | y
Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.
~ x
Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.
x ^ y
Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.