1. 程式人生 > 其它 >劍指offer-16題

劍指offer-16題

技術標籤:筆試演算法java

題目描述:

程式碼:

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");
            }
        }
    }
}

解析:

a^{n}=a^{n/2}\cdot a^{n/2}n為偶數時

a^{n}=a^{(n-1)/2}\cdot a^{(n-1)/2}\cdot an為奇數時

看起來就是個遞迴,對於a^{n/2}需要求兩次,如果用遞迴的話,要避免對a^{n/2}求兩次,一次遞迴就可以解決的。參考第一個方法,將遞迴算出的a^{n/2}平方一下即可,比第二種方法好。