按照递归来写的,结果报栈溢出。修改下方法,基本逻辑都没变,就没有栈溢出了,求答案。
public static void main(String[] args) {
double x = 2;
int n = -2147483648;
System.out.println(myPow(x,n));
}
public static double myPow(double x, int n) {
if(x == 0.0 || x == 1.0) {
return x;
}
if(n==0) {
return 1;
}
if(n<0) {
x = 1/x;
n = -n;
}
return pow(x,n);
}
public static double pow(double x, int n) {
if(n == 0) {
return 1;
}
if(n == 1) {
return x;
}
if(n%2 == 0) {
double y = pow(x, n/2);
return y * y;
}
else{
double y = pow(x, (n-1)/2);
return y * y * x;
}
}
修改后
public static void main(String[] args) {
double x = 2;
int n = -2147483648;
System.out.println(myPow2(x,n));
}
public static double myPow2(double x, int n) {
if (n == 0) {
return (double) 1;
}
if (n == 1) {
return x;
} else if (n == -1) {
return 1 / x;
}
if ((n % 2) == 0) {
double r = myPow(x, n / 2);
return r * r;
} else {
double r = myPow(x, n / 2);
return r * r * (n > 0 ? x : 1 / x);
}
}
展开