您的位置:首页 > 其它

LeetCode---(50)Pow(x, n)

2015-07-16 21:26 169 查看
Implement pow(x, n).

pow(x,n)就是求x的n次方。x的N次方可以看做:x^n = x^(n/2)*x^(n/2)*x^(n%2)。所以利用递归求解,当n==1的时候,x^n=x。

当然n是可以小于0的,2^(-3) = 1/(2^3)。按照上面那个规律就可以解决了。
class Solution {
public:
double myPow(double x, int n) {
if(n==0)
return 1.0;
if(n>0)
{
4000

double half=pow(x,n/2);
if(n%2==0)
return half*half;
else
return half*half*x;
}
if(n<0)
{
n=-n;
double half=pow(x,n/2);
if(n%2==0)
return 1.0/(half*half);
else
return 1.0/(half*half*x);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: