说明
地址: 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]
算法分析
- 这里用到的解决思路为二分法,比如2的10次方,等价于4的5次方,等价于4*(4的4次方),等价于4*(16的2次方),等价于4*(256的1次方).
- 需要考虑n的几个值
n == 0
返回1;n == 1
返回x;n == -1
x就要用x分之一, 并且n需要转为-n,同时需要考虑越界问题,解决为提取出多一个1/x
, 公式为1/x * pow(1/x, -(n + 1)
递归求解
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;
}
遍历求解
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;
}