[leedcode 69] Sqrt(x)

來源:互聯網
上載者:User

標籤:

Implement int sqrt(int x).

Compute and return the square root of x.

public class Solution {    //本題利用了牛頓迭代法:設r是f(x) = 0的根(x^2-k=f(x)),選取x0作為r初始近似值,過點(x0,f(x0))做曲線y = f(x)的切線L,L的方程為y = f(x0     //)+f‘(x0)(x-x0),求出L與x軸交點的橫座標 x1 = x0-f(x0)/f‘(x0),稱x1為r的一次近似值。    //過點(x1,f(x1))做曲線y = f(x)的切線,並求該切線與x軸交點的橫座標 x2 = x1-f(x1)/f‘(x1),稱x2為r的二次近似值。重複以上過程,得r的近似值     //序列,其中x(n+1)=x(n)-f(x(n))/f‘(x(n)),稱為r的n+1次近似值,上式稱為牛頓迭代公式。    //根據牛頓迭代的原理,可以得到以下的迭代公式:X(n+1)=[X(n)+p/Xn]/2    //還可以用常識性知識考慮,x=(x+k/x)/2        //本題注意點:    //1.返回結果要先聲明為double    //2.需要檢查參數的正負    //3.注意1e-6的寫法            public int mySqrt(int x) {        if(x<=0) return 0;        double res=1.0;        while(Math.abs(res*res-x)>1e-6){            res=(res+x/res)/2;        }        return (int)res;    }}

 

[leedcode 69] Sqrt(x)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.