一、题目
Implement pow(x, n).
二、代码
class Solution {
public:
double myPow(double x, int n) {
if (n<0){
double tmp=myPower(x,-n);
return 1.0/tmp;
}
else
return myPower(x,n);
}
double myPower(double x, int n) {
if (n==0)
return 1;
double tmp=myPower(x,n/2);
if (n%2==0)
return tmp*tmp;
else
return tmp*tmp*x;
}
};
三、思路
对n分情况进行,另开一个函数递归调用得到结果。