难度中等4
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
示例 1:
输入: 2.00000, 10 输出: 1024.00000
示例 2:
输入: 2.10000, 3 输出: 9.26100
示例 3:
输入: 2.00000, -2 输出: 0.25000 解释: 2-2 = 1/22 = 1/4 = 0.25
class Solution {
public:
double mp(double x , long n)
{
cout << n << ' ';
if(n == 0)
return 1;
if(n == 1)
return x;
double save = mp(x,n/2);
save *= save;
if(n%2 == 1)
return save*x;
else
return save;
}
double myPow(double x, int n) {
double res = x;
long num = n;
if(n == 0)
return 1;
if(num < 0)
{
num = abs(num);
res = 1/res;
}
cout << num << ' ' << res <<endl;
return mp(res,num);
}
};