题目
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
class Solution {
public:
double Power(double base, int exponent) {
if(0 == exponent) return 1;
if(1 == exponent) return base;
if(0.0 == base && exponent < 0) return 1;
base = exponent > 0 ? base : 1/base;
exponent = abs(exponent);
//通过移位运算符代替除2
double result = Power(base,exponent>>1);
result *= result;
//如果指数是奇数,通过位运算判断奇偶
if(1 == (exponent & 1))
{
result *= base;
}
return result;
}
};