50.pow(x,y)

leetcode(java實(shí)現(xiàn))


問題描述:

50.pow(x,y)
Implement pow(x, n), which calculates x raised to the power 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 [?2^31, 2^31 ? 1]

問題分析:

  • 【思路1-Java】遞歸實(shí)現(xiàn)

    采用遞歸實(shí)現(xiàn),那么本題的終止條件是 n == 0 和 n == 1。這里不采用下面的做法,因?yàn)闀r(shí)間復(fù)雜度為 O(n),加上題目的限制會(huì)超時(shí)。
    public class Solution {
    public double myPow(double x, int n) {
    if(n == 0) return 1;
    if(n == 1) return x;
    return myPow(x, n-1) * x;
    }
    }
    另外,本題的難點(diǎn)主要是在邊界條件:如果 n < 0,是不是 n = -n, x = 1 / x ,再進(jìn)行遞歸就能解決了呢?如果 n = Intege.MIN_VALUE,n = -n 會(huì)出現(xiàn)溢出,怎么辦呢?我們可以先將 n / 2 賦值給 t,再將 t = -n,就不會(huì)出現(xiàn)溢出問題。

  • 【思路2-Java】非遞歸實(shí)現(xiàn)

    m^n的理解:加入 n = 13,13在二進(jìn)制中表示為:00001101,那么13 = 2^3 + 2^2 + 2^0。

算法實(shí)現(xiàn):

參考代碼:

用方法二來實(shí)現(xiàn)

class Solution {
    public double myPow(double x, int n) {
        int exp = n<0 ? -n-1 : n;   //邊界和負(fù)值處理
        double product = 1;     //記錄結(jié)果
        for (double tmp = x; exp > 0; exp>>=1)
        {
            if ((exp&1) != 0)
                product *= tmp;     //如果二進(jìn)制位為1,則計(jì)算
            tmp *= tmp;     //記錄中間結(jié)果
        }
        return n<0 ? 1/product/x : product;     //正負(fù)及邊界處理
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些閱讀 2,144評論 0 2
  • 【程序1】 題目:古典問題:有一對兔子,從出生后第3個(gè)月起每個(gè)月都生一對兔子,小兔子長到第三個(gè)月后每個(gè)月又生一對兔...
    開心的鑼鼓閱讀 3,395評論 0 9
  • 在C語言中,五種基本數(shù)據(jù)類型存儲空間長度的排列順序是: A)char B)char=int<=float C)ch...
    夏天再來閱讀 4,060評論 0 2
  • 1. 關(guān)于診斷X線機(jī)準(zhǔn)直器的作用,錯(cuò)誤的是()。 (6.0 分) A. 顯示照射野 B. 顯示中心線 C. 屏蔽多...
    我們村我最帥閱讀 11,447評論 0 5
  • 這個(gè)冬天有點(diǎn)冷
    MrLii閱讀 517評論 0 2

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