HappyLeetcode64:Sqrt(x)

來源:互聯網
上載者:User

標籤:

Implement int sqrt(int x).

這道題本質上是求sqrt(x)下最大的整數。二分尋找是比較容易想到的方法。另,在網上又學習了下別人的牛頓迭代法。

這是我原來的寫法,寫入是錯誤的,複雜度太高

class Solution {public:    int sqrt(int x) {        if (x <= 0)            return 0;        if (x == 0 || x == 1)            return x;        long long start = 1;        long long end = x >> 1;        int index = start;        while (start <= end)        {            index = (start + end) >> 1;            if (index*index == x)                return index;            else{                if (end*end <= x)                    return end;                if (end - start == 1)                    return start;                if (index*index > x)                    end = index - 1;                if (index*index < x)                    start = index ;            }        }        return index;    }};

其實二分尋找的思想是對的,只不過在某些小細節上海需要尤為注意一下。

標準代碼可以這麼寫:

class Solution {public:    int sqrt(int x) {        long long i = 0;        long long j = x / 2 + 1;        while (i <= j)        {            long long mid = (i + j) / 2;            long long sq = mid * mid;            if (sq == x)                return mid;            else if (sq < x)                i = mid + 1;            else                j = mid - 1;        }        return j;    }};

完美的考慮了溢出的問題。這是我應該好好學習的地方。

牛頓迭代發解題

有此方法,可得到迭代公式xi+1=xi - (xi2 - n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2。

於是有如下代碼:

int sqrt(int x) {    if (x == 0) return 0;    double last = 0;    double res = 1;    while (res != last)    {        last = res;        res = (res + x / res) / 2;    }    return int(res);}

求解double的題目,可參考如上代碼

double sqrt(double x) {    if (x == 0) return 0;    double last = 0.0;    double res = 1.0;    while (!euqal(res,last))    {        last = res;        res = (res + x / res) / 2;    }    return res;}bool euqal(double num1, double num2){    if ((num1 - num2) < 0.0000001 && (num1 - num2) > -0.0000001)        return true;    else        return false;}

參考:

http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html

HappyLeetcode64: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.