AC Python solution, easy to understand, beat 75%, time complexity O(logN)


  • 0
    W

    class Solution(object):
    def myPow(self, x, n):

        def recur(x, n):
            if (n == 0):
                return 1
                
            if (n == 1):
                return x
            elif (n % 2) == 0:
                tmpVal = recur(x, n/2)
                return tmpVal * tmpVal
            else:
                tmpVal = recur(x, (n-1)/2)
                return x * tmpVal * tmpVal
                
        result = recur(x, abs(n))
        
        if (n < 0):
            result = 1 / result
            
        #print "result = ", result
        
        return result

Log in to reply
 

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