[Bit Operation-Simple] 231.2 Power of 2

[Title]
Given an integer, write a function to determine whether it is a power of 2.
[Example 1]
Input: 1
Output: true
Explanation: 20 = 1
[Example 2]
Input: 16
Output: true
Explanation: 24 = 16
[Example 3]
Input: 218
Output: false
[Code]
[Python]
Insert picture description here

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n&(n-1)==0 and n!=0

[Method 2]
Insert picture description here

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        dic=dict(Counter(bin(n)[2:]))
        return dic.setdefault('1',0)==1 and n>=0

[Method 3: Digital Method]
Insert picture description here

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if n<=0:
            return False
        while n>1:
            if n%2:
                return False
            n//=2
        return True

Guess you like

Origin blog.csdn.net/kz_java/article/details/115074146