Skip to content

Pow(x, n)

LeetCode

01 · Question

Implement pow(x, n), which calculates x raised to the power n (i.e., x^n).

Use fast exponentiation to achieve O(log n).

02 · Solution

Reference solution

1def myPow(x: float, n: int) -> float:
2 if n == 0:
3 return 1.0
4 if n < 0:
5 return 1.0 / myPow(x, -n)
6
7 half = myPow(x, n // 2)
8 if n % 2 == 0:
9 return half * half
10 return half * half * x