您的位置:首页 > 其它

50. Pow(x, n)

2016-12-11 21:41 197 查看
Implement pow(x, n).

幂运算

直接乘需要n-1次自乘,使用递归可以减少很多次乘法运算。

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