题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
思路
O(N)的解法是用循环每次乘以base,比较简单
O(logN)的解法是采用二分法的思想,即a^b = a^(b/2) * a^(b/2),……
a^(b/2) = a^(b/4) * a^(b/4),……a^2 = a* a以此类推,这里注意当exponent为奇数时,上述二分法的结果还要乘以base。
边界条件:
(1)base为0,且exponent为0时,所得结果是无效的。
(2)exponent为1时,所得结果都为1。
(3)考虑exponent正负数的情况。
代码
class Solution {
public:
double Power(double base, int exponent) {
g_InvalidInput =false;
if(base==0.0&& exponent==0) {g_InvalidInput = true;return 0.0;}
if(exponent==0) return 1.0;
unsigned int absexponent = (unsigned int )abs(exponent);//无论正负数,先取正
double value = Power_recursive(base,absexponent);//结果
if(exponent<0) value =1.0/value;//复数则求倒数
return value;
}
private:
bool g_InvalidInput;
double Power_recursive(double base,unsigned int exponent)
{
if(exponent == 0) return 1;
if(exponent == 1) return base;
double temp = base;
double total = 1;
for(int i=2;i<=exponent;i*=2)
{
total = temp * temp;
temp = total;
}
if(exponent&0x1) total*=base;//整次方为奇数时,需再乘以base
return total;
}
};