Problem
Implement pow(x, n), which calculates $x$ raised to the power $n (x^n)$.
Example 1:
1 | |
Example 2:
1 | |
Example 3:
1 | |
Note:
- $-100.0 < x < 100.0$
- $n$ is a 32-bit signed integer, within the range [$−2^{31}$, $2^{31} − 1$]
Explanation
-
Let’s see an example first, $2^4 = 4^2 = 16^1$.
-
We can divide the
powerby 2 and multiple thebaseby itself untilpoweris 1. -
Default the
resequal 1, if thepoweris an odd number, we can multiple theresby base, then power subtract 1 to become even. -
If
poweris a negative number, we can revertpowerto positive then after we get the finalres, we use 1 to divide theres. -
The corner case is the minimum of integer is
-2147483648and the maximum of integer is2147483647, which is 1 less than the revert of minimum integer. In order to fix it, before we revert the negativepower, we add 1 to it, andresmultiple by thebasebecause $-2147483648 + 1 = -2147483647$, when we revert it can be a maximum integer now, but we multiple the base one time less, so that is why we multiple theresbybase.
Solution
1 | |