[leetcode]Sqrt(x)

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   for   ar   div   

Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

【注意】:

1. 本題int類型可能會溢出,因此不能用乘法運算,應盡量用除法。

2. 絕大多數數字都不是可開方的,該如何得到比較近的結果呢?

演算法思路:

思路1:順序遍曆肯定不需要試了,二分尋找比較靠譜。二分法在數值計算中非常常見,需要熟練掌握。

代碼如下:

public class Solution {    public int sqrt(int x) {        if(x <= 1) return x == 0 ? 0 : x;        int l = 1, r = x /2 + 1 ;        while(l <= r){            int mid = (l + r) / 2;            if(mid <= x / mid && (mid + 1) > x / (mid + 1)){                return mid;//這裡用的很巧妙            }else if(mid > x / mid){                r = mid - 1;            }else{                l = mid + 1;            }        }        return 0;    }}

思路2:牛頓迭代法;比較高大上,詳細分析過程請戳這裡。

代碼如下:  

 1 public int sqrt(int x) { 2     if (x == 0) return 0; 3     double lastY = 0; 4     double y = 1; 5     while (y != lastY) 6     { 7         lastY = y; 8         y = (y + x / y) / 2; 9     }10     return (int)(y);11 }

 這道題出的很好

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.