Power of Two --- Solution, any suggestions in interview


  • 0
    W
     class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n<=0:
            return False
        if n ==1:
            return True
    
        result = self.recur(abs(n),[])
        #print result
       # print result
        if not result:
            return False
        else:
            if result[0] ==0:
                return True
            else:
                return False
    
    def recur(self,n,result):
        if n<=2:
           # print result
            result.append(n%2)
            return result
        if n%2==0:
            self.recur(n/2,result)
        return result

  • 0
    R
    class Solution(object):
    def isPowerOfTwo(self, n):
        #principle: if n is num of 2, the binary n only contain a 1
        has1 = 0
        if n == 0: return False
        elif n == 1: return True
        else:
            while n >= 1 and has1 <= 1:
                if n % 2 != 0:
                    has1 += 1
                n = n/2
            if has1 == 1:
                return True
            return False

Log in to reply
 

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