数值的整数次方
实现函数double Power(double base, int exponent),求base的 exponent次方。
不得使用库函数,同时不需要考虑大数问题。
只要输出结果与答案的绝对误差不超过 10−2 即视为正确。
注意:
不会出现底数和指数同为0的情况
当底数为0时,指数一定为正
样例1
输入:10 ,2
输出:100
样例2
输入:10 ,-2
输出:0.01
- 完美解法,普通的幂的运算,速度太慢,无法通过,这一题运用了二进制的运算思想
你比如说,3的10次方
10==100101.首先判断最末尾是否为1,如果不为1,
则,x=33,记录x
10010整体右移一位
则为01001
2.继续判断最末尾是否为1,
为一,则最终的结果x
class Solution {
public:
double Power(double x, int n) {
typedef long long LL;
bool is_minus= n<0;
double res=1;
for(LL k=abs(LL(n));k;k>>=1)
{
if(k&1)
res*=x;
x*=x;
}
if(is_minus) res=1/res;
return res;
}
};
class Solution {
public:
double Power(double x, int n) {
double res=1;
for(long long k=abs((long long) (n));k;k>>=1)
{
if(k&1)
res*=x;
x*=x;
}
if(n<0) res=1/res;
return res;
}
};
class Solution {
public:
double Power(double x, int n)
{
double res=1;
for(long long i=abs((long long)n);i;i>>=1)
{
if(i&1)
res*=x;
x*=x;
}
return n<0?1/res:res;
}
};