面试题16:数值的整数次方
Posted flyingrun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面试题16:数值的整数次方相关的知识,希望对你有一定的参考价值。
本题考查库函数的实现原理,特别注意用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;
}
以上是关于面试题16:数值的整数次方的主要内容,如果未能解决你的问题,请参考以下文章