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
power
by 2 and multiple thebase
by itself untilpower
is 1. -
Default the
res
equal 1, if thepower
is an odd number, we can multiple theres
by base, then power subtract 1 to become even. -
If
power
is a negative number, we can revertpower
to positive then after we get the finalres
, we use 1 to divide theres
. -
The corner case is the minimum of integer is
-2147483648
and 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, andres
multiple by thebase
because $-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 theres
bybase
.
Solution
1 |
|