劍指offer-16題
阿新 • • 發佈:2021-02-14
題目描述:
程式碼:
public class Design { static double PowerWithExponent(double base, int exponent) { // base為0的處理 if (base == 0) { if (exponent < 0) { return 0; } else { return 1; } } if (exponent == 0) { return 1; } if (exponent == 1) { return base; } int temp = exponent; if (exponent < 0) { temp = -temp; } double result = PowerWithExponent(base, temp >> 1); result *= result; if ((temp & 1) == 1) { result *= base; } if (exponent < 0) { return 1 / result; } return result; } static double PowerWithExponentTired(double base, int exponent) { // base為0的處理 if (base == 0) { if (exponent < 0) { return 0; } else { return 1; } } if (exponent == 0) { return 1; } if (exponent == 1) { return base; } int temp = exponent; if (exponent < 0) { temp = -temp; } double result = PowerWithExponentTired(base, temp >> 1) * PowerWithExponentTired(base, temp >> 1); if ((temp & 1) == 1) { result *= base; } if (exponent < 0) { return 1 / result; } return result; } public static void main(String[] args) throws Exception { double base = -2.0; for (int i = -100; i < 101; i++) { double first = PowerWithExponent(base, i); double second = PowerWithExponentTired(base, i); if (first != second) { System.out.println("bad bad"); } } } }
解析:
當為偶數時
當為奇數時
看起來就是個遞迴,對於需要求兩次,如果用遞迴的話,要避免對求兩次,一次遞迴就可以解決的。參考第一個方法,將遞迴算出的平方一下即可,比第二種方法好。