Skip to main content

50. Pow(x, n)

https://leetcode.com/problems/powx-n/

Python

from functools import cache
class Solution:
@cache
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1

if n == 1:
return x

if n == -1:
return 1/x

base = self.myPow(x, n%2)
exp = self.myPow(x, n//2)

return exp * exp * base