LintCode x的n次冪

題目

實(shí)現(xiàn) pow(x,n)

注意事項(xiàng)

不用擔(dān)心精度,當(dāng)答案和標(biāo)準(zhǔn)輸出差絕對(duì)值小于1e-3時(shí)都算正確

樣例
Pow(2.1, 3) = 9.261
Pow(0, 1) = 0
Pow(1, 0) = 1

分析

二分法遞歸
詳細(xì)見(jiàn)代碼注釋

代碼

public class Solution {
    /**
     * @param x the base number
     * @param n the power number
     * @return the result
     */
    public double myPow(double x, int n) {

        // Write your code here
        if (x == 0) {
            return 0;
        }
        
        // base case: when n = 0, the result is 1;
        if (n == 0) {
            return 1;
        }
        
        /*
        遞歸的主體部分
        */
        
        // X^(-n) = X^(n + 1) * X
        // X^n = 1/(x^(-n))
        if (n < 0) {
            double ret = x * myPow(x, -(n + 1));
            return (double)1/ret;
        }
        
        // 將求pow對(duì)半分。再將結(jié)果相乘
        double ret = myPow(x, n / 2);
        ret = ret * ret;
        
        //如果有余數(shù),再乘以x本身。
        if (n % 2 != 0) {
            ret = ret * x;
        }
        
        return ret;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容