题目 数值的整数次方
实现函数double Power(double base, int exponent),求base的exponent次方
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
解1 循环
快速幂法的二进制角度:
class Solution {
public:
double Power(double base, int exponent) {
int e = abs(exponent);
double res = 1;
while(e)
{
if(e & 1 == 1) res*=base;
base *= base;
e >>= 1;
}
return exponent > 0 ? res : 1/res;
}
};
解2 递归
二分法角度:
class Solution {
public:
double myPow(double x, long long n) {
//异常处理
if(0 == x)
{
if(n<0) return -1;
else return 0;
}
//n=0,返回1
if(0 == n) return 1;
//n=2,直接返回两数相乘
if(2 == n) return x*x;
//若n为负数,则x^n实际上为(1/x)^(-n)
if(n<0){n = -n ; x = 1/x;}
//递归
double res = myPow(x,n>>1);
return (n&1) == 1 ? res*res*x : res*res;
}
};
参考题解:力扣官方题解
https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/solution/mian-shi-ti-16-shu-zhi-de-zheng-shu-ci-fang-kuai-s/