- categories: Code, Interview Question, leetcode, Medium
- source: https://leetcode.com/problems/powx-n
- topics: Mathematics, Recursion
Implement pow(x, n), which calculates x
raised to the power n
Idea
Use the recursion to reduce the number of multiplications
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
if n == 1:
return x
if n < 0:
return self.myPow(1 / x, -n)
if n % 2 == 0:
return self.myPow(x * x, n // 2)
else:
return x * self.myPow(x * x, n // 2)