Python n&(n-1) and iterative ways


  • 0
    W

    n&(n-1) way:

    class Solution(object):
        def isPowerOfTwo(self, n):
            """
            :type n: int
            :rtype: bool
            """
            return False if n<1 else (n-1)&n==0
    

    Iterative way:

    class Solution(object):
        def isPowerOfTwo(self, n):
            """
            :type n: int
            :rtype: bool
            """
            if n<=1:
                return True and not n<1
            else:
                while n>1:
                    if n%2!=0:
                        return False
                    n /= 2
                return True
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.