[LeetCode] 69. Sqrt(x)

來源:互聯網
上載者:User

標籤:output   ++   NPU   思想   想去   turned   個數   數字   ati   

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4Output: 2

Example 2:

Input: 8Output: 2Explanation: The square root of 8 is 2.82842..., and since              the decimal part is truncated, 2 is returned.


題意:開方
這裡肯定是不使用Math庫的前提下,
我們可以利用二分的思想去開方,開方反過來就是平方,Integer.MAX_VALUE 開方是46340,也就是最大的解,因為存在越界的情況
這個數字需要我們提前算出來。之後只要二分去找,mid*mid <= target , (mid+1)*(mid+1) > target 就行了
class Solution {    public int mySqrt(int x) {        int l = 0;        int r = 46340;        if (r*r < x)            return r;        if (x == 1 || x == 0)            return x;        while (r - l > 5) {            int mid = (l + r) / 2;            if (mid * mid < x) {                l = mid;            }            else if (mid * mid > x) {                r = mid;            }            else                return mid;        }        for (int i = l; i <= r; i++) {            if (i*i == x)                return i;            if (i*i < x && (i+1)*(i+1) > x)                return i;        }        return 0;    }}

 

[LeetCode] 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.