LeetCode代碼分析——50. Pow(x, n)(細(xì)節(jié),int上下限)

題目描述

Implement pow(x, n), which calculates x raised to the power n (xn).
實(shí)現(xiàn)x的n次方操作。

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

Note:

  • -100.0 < x < 100.0
  • n is a 32-bit signed integer, within the range [?231, 231 ? 1]

思路分析

這個(gè)題很簡(jiǎn)單,最簡(jiǎn)單的方法是遍歷,result*=x;,

  • 但是這樣的話復(fù)雜度是O(n)。還可以靈活利用已有的結(jié)果來(lái)降低復(fù)雜度,通過(guò)遞歸,以210為例,可以將210遞歸為25 * 25,依次向下求解。
  • 另一方面注意到n的范圍是全部int的范圍,而int的范圍是不對(duì)稱的([?231, 231 ? 1]),因此需要注意負(fù)數(shù)處理時(shí)不能直接將n取-n(通過(guò)x-(n+1)*x遞歸,或者對(duì)Integer.MIN_VALUE進(jìn)行特殊判斷)。
  • 另外注意在對(duì)奇偶進(jìn)行判斷和除2時(shí)盡量使用位運(yùn)算>> << & |),可以更好的利用計(jì)算機(jī)二進(jìn)制的特性提升性能。(《劍指offer》

代碼實(shí)現(xiàn)

public class Solution {

    /**
     * 304 / 304 test cases passed.
     *  Status: Accepted
     *  Runtime: 22 ms
     * @param x
     * @param n
     * @return
     */
    public double myPow(double x, int n) {
        if (n < 0) {
            return 1 / x * myPow(1 / x, -(n + 1));
        }
        if (n == 0) {
            return 1;
        }
        if (n == 1) {
            return x;
        }

        double half = myPow(x, n >> 1);
        half *= half;

        if ((n & 1) == 1) {
            half *= x;
        }

        return half;
    }

}
?著作權(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)容