Solution 1: key is to deal with all corner case and use temp to store mid result.
public class Solution {
public double myPow(double x, int n) {
if (x==1) return 1;
if (x==-1) return (n%2==1)?-1:1;
if (x==0) return 0;
if (n==0) return 1;
if (n<0) return 1/myPow(x,-n);
if (n==1) return x;
double mid=myPow(x,n/2);
double res=mid*mid; //important here, make sure mid is only cal one time
if (n%2==1) res*=x;
return res;
}
}
没有评论:
发表评论