1. 问题描述
实现函数:
double power(double base,int exponent)
求base的exponent次方,不使用库函数,不考虑大数问题。
2. 解法1
考虑边界问题;
#include <iostream>
#include <string>
using namespace std;
#define DBL_MIN 0.000001
double power(double base, int exponent)
{
if ( base < DBL_MIN && base > -DBL_MIN)
{
return 0.0;
}
double result = 1.0;
int unsignedExponent = exponent;
if (exponent < 0)
{
unsignedExponent = -exponent;
}
for (int i = 1; i < unsignedExponent; i++)
{
result *= base;
}
if (exponent < 0)
{
result = 1.0 / result;
}
return result;
}
int main(int argc, const char * argv[])
{
double base = 12.0;
int exponent = -2;
cout<<"base = "<<base<<"; exponent = "<<exponent<<"; The result is: "<<power(base, exponent)<<endl;
base = 0.0;
exponent = 2;
cout<<"base = "<<base<<"; exponent = "<<exponent<<"; The result is: "<<power(base, exponent)<<endl;
base = -0.000000009;
exponent = 12;
cout<<"base = "<<base<<"; exponent = "<<exponent<<"; The result is: "<<power(base, exponent)<<endl;
return 0;
}
2. 解法2
假设求解32次方,如果已知16次方,那么只要在16次方的基础上再平方一次就可以了,而16次方是8次方的平方,一次类推。
#include <iostream>
#include <string>
using namespace std;
#define DBL_MIN 0.000001
double powerUnsignedExponent(double base, int exponent)
{
if (exponent == 0)
{
return 1.0;
}
if (exponent == 1)
{
return base;
}
// exponent >> 1 == exponent / 2
double result = powerUnsignedExponent(base, exponent>>1);
result *= result;
// if exponent is odd
if ((exponent & 0x01) == 1)
{
result *= base;
}
return result;
}
double power(double base, int exponent)
{
if ( base < DBL_MIN && base > -DBL_MIN)
{
return 0.0;
}
double result = 1.0;
int unsignedExponent = exponent;
if (exponent < 0)
{
unsignedExponent = -exponent;
}
result = powerUnsignedExponent(base, unsignedExponent);
if (exponent < 0)
{
result = 1.0 / result;
}
return result;
}
int main(int argc, const char * argv[])
{
double base = 12.0;
int exponent = -2;
cout<<"base = "<<base<<"; exponent = "<<exponent<<"; The result is: "<<power(base, exponent)<<endl;
base = 0.0;
exponent = 2;
cout<<"base = "<<base<<"; exponent = "<<exponent<<"; The result is: "<<power(base, exponent)<<endl;
base = -0.000000009;
exponent = 12;
cout<<"base = "<<base<<"; exponent = "<<exponent<<"; The result is: "<<power(base, exponent)<<endl;
return 0;
}
参考:《剑指offer 名企面试官精讲典型编程题》 - 面试题11:数值的整数次方