Explanation
Address: https://leetcode.com/problems/powx-n/
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
-100.0 < x < 100.0
n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1]
Analysis of Algorithms
- Solutions as used herein dichotomy, 10 such as power of 2, 4 is equivalent to the fifth power, equivalent to (the fourth power of 4) * 4, 4 * is equivalent to the power of 2 (16 ), is equivalent to a power of 4 * (256).
- We need to consider several values of n
n == 0
Return 1;n == 1
Return x;n == -1
x x points necessary to use one, and needs into n -n, also need to consider cross-border issues, solve for the extracted one more1/x
, the formula is1/x * pow(1/x, -(n + 1)
Recursive solution
public double myPow(double x, int n) {
if (n < 0) {
// consider -n overflow
return 1/x * myPow(1/x, -(n + 1));
}
if (n == 0) {
return 1;
}
if (n == 1) {
return x;
}
int halfN = n >> 1;
return (n%2 == 0) ? myPow(x * x, halfN) : myPow( x * x, halfN) * x;
}
Solving traversal
public double myPowWithIterate(double x, int n) {
double result = 1;
if (n < 0) {
// consider -n overflow
x = 1/x;
n = -(n + 1);
result = x;
}
while (n != 0) {
if (n % 2 == 1) {
result *= x;
if (n == 1) {
break;
}
}
x = x * x;
n = n >> 1;
}
return result;
}