pow(x,n) in python


  • 0
    J
    def myPow(x, n):
        def posPow(x, n):
            if n == 1:
                return x
            if n in cache:
                return cache[n]
            else:
                if n % 2 == 0:
                    cache[n] = posPow(x, n // 2) * posPow(x, n // 2)
                else:
                    cache[n] = x * posPow(x, n // 2) * posPow(x, n // 2)
                return cache[n]
    
        cache = dict()
        if n == 0:
            return 1.0
        if n < 0:
            return 1.0 / posPow(x, abs(n))
        else:
            return posPow(x, n)
    

Log in to reply
 

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