Implement pow(x, n), 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