Implement pow(x, n).
Subscribe to see which companies asked this question
//思路:主要考察越界,n为负数等问题
方法一:API
public class Solution {
public double myPow(double x, int n) {
// double Math.pow(double ,double)
if(x==0){return 0;}
if(n==1){return x;}
double result=Math.pow(x,n);
return result;
}
}
方法二://考虑 n=负数边界
public class Solution {
public double pow(double x, int n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return x;
}
boolean isNegative = false;
if (n < 0) {
isNegative = true;
n *= -1;
}
int k = n / 2;
int l = n - k * 2;
double t1 = pow(x, k);
double t2 = pow(x, l);
if (isNegative) {
return 1/(t1*t1*t2);
} else {
return t1*t1*t2;
}
}
}