題目描述:
實現函數
double Power(double base, int exponent)
,求base的exponent次方,不得使用庫函數,同時不需要考慮大數問題
思路:本題的重點考察內容是代碼的完整性,要綜合考慮輸入的合法性,邊界值等等,同時也可以進行優化
實現一:
public double Power(double base, int exponent){
double result = 1.0;
for(int i = 0; i < exponent; i++){
result *= base;
}
return result;
}
這裏沒有考慮任何輸入的非法性以及指數的負數情況。
實現二:
boolean g_InvalidInput = false;
public double Power(double base, int exponent){
g_InvalidInput = false;
if(equal(base, 0.0) && exponent < 0){
g_InvalidInput = true;
return 0.0;
}
int absExp = Math.abs(exponent);
double result = PowerWithPositiveExp(base, absExp);
if(exponent < 0){
result = 1.0/result;
}
return result;
}
public static double PowerWithPositiveExp(double base, int exp){
double result = 1.0;
for(int i = 0; i < exp; i++){
result *= base;
}
return result;
}
public static boolean equal(double d1, double d2){
if((d1 - d2 > -0.0000001) && ( d1 - d2 < 0.0000001)){
return true;
}else{
return false;
}
}
上述程序中對輸入參數進行了合法性檢查,同時設計了全局變量來標記輸入的合法性表示。
但是上述代碼還是不夠高效。
實現3
public static double PowerWithPositiveExp(double base, int exp){
if(exp == 0){
return 1;
}
if(exp == 1){
return base;
}
double result = PowerWithPositiveExp(base, exp >> 1);
result *= result;
if(exp & 0x1 == 1){
resutl *= base;
}
return result;
}
這裏利用了公式:
a^n = a^(n/2)* a^(n/2)*base
其中n爲偶數時, base = 1; n爲奇數時,base = a.
另外:使用位運算提高效率
除以2等價於 >> 1
模 2等價於 & 0x1