本题考查库函数的实现原理,特别注意用O(logn)时间求a的n次方的优化算法。
C++版
#include <iostream>
#include <cmath>
using namespace std;
bool g_InvalidInput = 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 & 0x1) == 1)
result *= base;
return result;
}
double Power(double base, int exponent){
g_InvalidInput = false;
if(base == 0.0 && exponent < 0){
g_InvalidInput = true;
return 0.0;
}
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;
}
int main()
{
cout << "Hello world!" << endl;
cout<<Power(2,3)<<endl;
return 0;
}
用O(logn)时间求a的n次方的优化算法。
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 & 0x1) == 1)
result *= base;
return result;
}