快速幂

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;
}
};

posted @ 2019-03-19 15:30  zzas12345  阅读(125)  评论(0编辑  收藏  举报