Implement pow(x, n).
Subscribe to see which companies asked this question.
思路就是用到递归,代码如下:
double myPow(double x, int n) {
if(n==0)
return 1.0;
if(n<0)
return 1.0/myPow(x,-n);
return x*myPow(x,n-1);
}
此时会发生溢出错误。这道题难就难在如何处理边界问题。
Accept code:
class Solution {
public:
double myPow(double x, int n) {
if(n<0) return 1.0/myPow_1(x,-n);
else return myPow_1(x,n);
}
double myPow_1(double x,int n)
{
if(n==0) return 1.0;
double y=myPow_1(x,n/2);
if(n&1) return y*y*x;
else return y*y;
}
};
转载请注明原文地址: https://ju.6miu.com/read-22673.html