思路:快速幂
Java实现的过程中,需要把int转long,因为负数会溢出。
代码:
class Solution {
public double myPow(double x, int n) {
long N = n;
if (n < 0) {
return 1.0 / Pow(x, -N);
}
return Pow(x, N);
}
public double Pow(double x, long n) {
if (n == 0) {
return 1.0;
}
double temp = Pow(x, n / 2);
if (n % 2 == 0) {
return temp * temp;
}
return temp * temp * x;
}
}