Problem
Implement pow(x, n), which calculates x raised to the power n ( x n x^n xn).
Algorithm
Fast pow algorithm. Divide and conquer.
Code
class Solution:
def myPow(self, x: float, n: int) -> float:
def qpow(x, n):
if n == 0:
return 1
if n == 1:
return x
y = qpow(x, n // 2)
if n % 2 == 1:
return y * y * x
else:
return y * y
if n == 0:
return 1
elif n > 0:
return qpow(x, n)
else:
return qpow(1/x, -n)