Topic:
Given an integer, write a function to determine if it is a power of.
class solution (Object): def ispoweroftwo (self, N): # """ : Type n:int : Rtype:bool " " "
Methods: Analyze the characteristics of power of 2, found that 2 of any number of squares, into the binary system only the first is 1 the remaining bits 0, so my solution is as follows:
class solution (Object): def ispoweroftwo (self, N): return if Else if bin (n). Count ('1'else False)
The bin function converts a given number into a binary, which is returned as a string, so it is only possible to check the return value of the bin if it contains a ' 1 '.
Decomposing the line of code above to see
class solution (Object): def ispoweroftwo (self, N): if n<0: return False returnif bin (n). Count ('1'else False
Then see the other solution is mainly n& (n-1) ==0, this method is also the use of the power of the 2 side of the characteristics, n if the power of 2, then (n-1) binary number only the highest bit is 0, the remaining bits are all 1, so let n& (n-1) bitwise AND, if equal to 0, Indicates that n is a power of 2
Python Leetcode diary--231. Power of