Recursive Solution for myPow(x,n) in Python, Runtime: O(log(n))


  • 0
    class Solution(object):
        def myPow(self, x, n):
            """
            :type x: float
            :type n: int
            :rtype: float
            """
            if n < 0: return self.myPow(1/x,-n)
            if n == 0: return 1
            rest = self.myPow(x,n//2)
            if n % 2 == 0:
                return rest * rest
            else: # n is odd
                return x * rest * rest
    

Log in to reply
 

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