问题可以采用递归的形式求解,但是边界处理为易错点,好吧,承认处理了挺久的。
递归解法:
class Solution {
public double myPow(double x, int n) {
if (n==0) {
return 1.0;
}
if(n == Integer.MIN_VALUE){
return myPow(x*x, n/2);
}
if (n<0) {
n=-n;
x=1/x;
}
if (n%2==0) {
return myPow(x*x,n/2);
}else{
return x*myPow(x*x,n/2);
}
}
}
非递归解法:
class Solution {
public double myPow(double x, int n) {
if(x==1||x==-1){
if (x==-1&&n%2==0) {
return -x;
}
return x;
}//处理x=-1或x=1的情况
if (n<0) {
x=(double)1/x;
n=-n;
if(n==Integer.MIN_VALUE){
return 0;
}//注意,如果没有这句,会输出无穷,但是加了这一句之后,结果直接给返回0
}
double pow=1;
while(n!=0){
if ((n&1)!=0) {
pow*=x;
}
x*=x;
n=n>>1;
}
return pow;
}
}