50. Pow(x, n)
Description
描述:https://leetcode.com/problems/powx-n/description/
题意:求 x 的 n 次方。
Solution: (Java)
class Solution {
public double myPow(double x, int n) {
if (n == 0)
return 1;
int m = n / 2; // 先n/2,避免n=Integer.MIN_VALUE时取绝对值溢出
if (n < 0) { // 注意n<0的情况
m = -m;
x = 1 / x;
}
double ret = myPow(x, m);
if (n % 2 == 0)
return ret * ret;
return ret * ret * x;
}
}
思路
- 不能简单地使用递归,会有各种溢出问题;
- 使用二分法进行递归,减少计算量;
- 先
n / 2
,避免n=Integer.MIN_VALUE
时取绝对值溢出。