[Java]Leetcode69 Sqrt(x)

來源:互聯網
上載者:User

標籤:

Implement int sqrt(int x).Compute and return the square root of x.

題意:算一個數的平方根。

好不容易想到用二分尋找來解決改題,但是也破費了點力氣,放到eclipse中調試來出來。注意點就是:取中值相乘,有可能會超過整數的最大範圍,所以比較的時候就會出錯。所以在定義的時候全部定義為long型。

第一版:

 public int mySqrt(int x){if (x == 0)return 0;long low = 1;long high = x;long tmp;long mid = 1;while (low <= high)//二分尋找{mid = (low + high) / 2;tmp = mid * mid;if (tmp == x)return (int)mid;else if (tmp > x)high = mid - 1;else if (tmp < x)low = mid + 1;}return (int)((mid*mid)>x?mid-1:mid);}

我們可以將上述的代碼再改進一下:

public int mySqrt(int x){long low = 0;long high = x/2+1;//平方根的值按規律發現不會大於它的中值+1。這樣每個尋找就少了一次long tmp;long mid = 1;while (low <= high){mid = (low + high) / 2;tmp = mid * mid;if (tmp == x)return (int)mid;else if (tmp > x)high = mid - 1;else if (tmp < x)low = mid + 1;}return (int)high;}


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

[Java]Leetcode69 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.