Implement pow(x, n).
public class Solution {
public double pow(double x, int n) {
if(n==0) {
return 1;
} else if(n==1) {
return x;
} else if(n<0){
n *= -1;
x = 1/x;
}
double tmp = pow(x, n/2);
if(n%2==0) {
return tmp * tmp;
} else {
return tmp * tmp * x;
}
}
}
=========
public class Solution {
public double myPow(double x, int n) {
if (n == 0) {
return 1;
}
if (n < 0) {
return 1.0 / myPow(x, -(n + 1)) * 1.0 / x;
}
double y = myPow(x, n / 2);
if (n % 2 == 0) {
return y * y;
} else {
return y * y * x;
}
}
}
没有评论:
发表评论