Challenge Description
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
|
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
|
Note:
-100.0 < x < 100.0
n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1]
Solution
Two branch for computing pow(x, n)
with divide and conquer approach.
When n
is odd, pow(x, n) = x * pow(x, n-1)
When n
is even, pow(x, n) = pow(x, n/2) * pow(x, n/2).
Note when x is equal with 1.0, we could do a optimization here.
Another corner case is when n
is -2^31, -n
will trigger a integer overflow.
|
Join my Email List for more insights, It's Free!😋