首页 > 其他 > 详细

快速幂

时间:2019-03-19 15:49:42      阅读:122      评论:0      收藏:0      [点我收藏+]

Implement pow(xn), which calculates x raised to the power n (xn).

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100
思路:快速幂,直接乘就可以了2^10=2^8*2^2;注意各一个int的溢出问题,将int改成long就可以了。

class Solution {
public:
double myPow(double x, long n) {
if(n==0) return 1;
if(n<0) return 1/myPow(x,-n);
double res=1.0,base=x;
while(n){
if(n&1)res*=base;
base*=base;
n=n>>1;
}
return res;
}
};

快速幂

原文:https://www.cnblogs.com/zzas0/p/10558990.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!