Any faster python way?

  • 0

    Hi everyone, I was trying to solve this problem, and I have tried four different accepted ways

    But none of them is faster than 50ms, this is very slow according to the statistical result.

    Any advice how to improve?

    class Solution(object):
        def isPowerOfTwo(self, n):
            :type n: int
            :rtype: bool
            ## recursive
            if n==0:
                return False
            elif n==1:
                return True
            elif n%2!=0:
                return False
                return self.isPowerOfTwo(n/2)
            ## count bit
            return n>0 and len([i for i in range(32) if (1&n>>i)])==1
            ## 2**30 math
            return n>0 and (1073741824 % n == 0)
            ## n-1 trick
            return n>0 and n&(n-1)==0

  • 0
    This post is deleted!

Log in to reply

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