Pow(x, n)

LeetCode

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

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

Use fast exponentiation to achieve O(log n).

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
idx
10
0
5
1
Step 1 / 3
Step 1:
Compute myPow(2, 10). Split into half exponent: myPow(2, 5).
Pointers: idx=0
Focus: select @ [0]