例如:2^8可以理解为两个2^4相乘,而2^4是两个2^2相乘,2^2是两个2相乘,所以一共只计算了三次,用递归的方法比较高效。
bool Equal(double num1,double num2)
{
if((num1-num2 > -0.00001) && (num1-num2 < 0.00001))
return true;
else
return false;
}
double PowerWithUnsignedExponent(double base,unsigned int exponent)
{
if(exponent == 0)
return 1;
if(exponent == 1)
return base;
double result = PowerWithUnsignedExponent(base,exponent >> 1);
result *= result;
if((exponent & 1) == 1)
result *= base;
return result;
}
bool g_InvalidInput = false;
double Power(double base,int exponent)
{
g_InvalidInput = false;
if(Equal(base,0.0)&&exponent<0)
g_InvalidInput = true;
unsigned int absExponent = (unsigned int) exponent;
if(exponent < 0)
absExponent = (unsigned int) (-exponent);
double result = PowerWithUnsignedExponent(base,absExponent);
if(exponent < 0)
result = 1.0 / result;
return result;
}
用右移运算符替代除以2,用位与运算符判断奇数和偶数