實現(xiàn)函數(shù) double Power(double base, int exponent),求 base 的 exponent 次方。不得使用庫函數(shù),同時不需要考慮大數(shù)問題。
解析:該題需要首先考慮底數(shù)為 0 的情況,當指數(shù)也為 0 的時候是非法輸入,和面試館要商量好計算結(jié)果,我這里是 1.0;當指數(shù)為負數(shù)的時候也是非法輸入,因為 ;當指數(shù)為正數(shù)的時候可以安全返回 0.0。底數(shù)為 0 的情況考慮結(jié)束之后,如果指數(shù)是負數(shù),那就先計算指數(shù)是正數(shù)的結(jié)果,然后將最后結(jié)果的倒數(shù)返回;如果指數(shù)是正數(shù)就返回計算結(jié)果就好。計算的方法是經(jīng)典的快速冪求法:將指數(shù)不斷右移一位,將結(jié)果翻一番,直到指數(shù)變?yōu)?,將結(jié)果乘以底數(shù)并返回。注意,使用右移的速度要比除以 2 要快。
答案:
bool g_InvalidInput = false;
bool equal(double num1, double num2);
double PowerWithUnsignedExponent(double base, unsigned int exponent);
double Power(double base, int exponent)
{
//由于測試是連續(xù)的,上一次的全局變量可能被置為 true,所以這個時候要還原
g_InvalidInput = false;
if (equal(base, 0.0))
{
if (exponent == 0)
{
g_InvalidInput = true;
return 1.0;//和面試官約定好返回數(shù)值
}
else if (exponent < 0)
{
g_InvalidInput = true;// 0 的負數(shù)次方會導致除 0,所以是非法
return 0.0;
}
else return 0.0;
}
unsigned int absExp = exponent>=0 ?
static_cast<unsigned int>(exponent) :
static_cast<unsigned int>(-exponent);
double res = PowerWithUnsignedExponent(base, absExp);
if (exponent<0) return 1.0/res;
else return res;
}
double PowerWithUnsignedExponent(double base, unsigned int exponent)
{
if (exponent == 0) return 1.0;
if (exponent == 1) return base;
if (exponent == 2) return base * base;
unsigned int exp = exponent;
double ret = base;
while (exp >= 2)
{
exp >>= 1;
ret *= ret;
}
if (exp == 1) ret *= base;
return ret;
}
bool equal(double num1, double num2)
{
//將差值的絕對值控制在 0.0000001 之內(nèi)
return (num1 - num2 > -0.0000001) && (num1 - num2 < 0.0000001);
}