【题目描述】
Implement pow(x, n).
【思路】
采用递归的思路,需要注意的是要判断边缘样例,如n=0和n=-1的情况,另外当x=0时候要分n等于-1和n不等于-1两种情况讨论。
【代码】
class Solution {
public:
double myPow(double x, int n) {
double tmp=x;
if(x==0){
if(n==-1) return INT_MIN;
else return 0;
}
if(n==0) return 1;
if(n==-1) return 1/x;
tmp=myPow(x,n/2);
if(n%2==0) return tmp*tmp;
else{
if(n>0) return tmp*tmp*x;
else return tmp*tmp/x;
}
}
};