Leetcode: Sqrt(x)

來源:互聯網
上載者:User

.

就高興了,直接二分吧。但是要注意,即使用long long都TM越界,還要用unsigned long long。最後返回值還要再檢查一下。

int sqrt(int x) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        unsigned long long begin = 0;        unsigned long long end = (x+1)/2;        unsigned long long mid;        unsigned long long tmp;        while(begin < end)        {            mid = begin + (end-begin)/2;            tmp = mid*mid;            if(tmp==x)return mid;            else if(tmp<x) begin = mid+1;            else end = mid-1;        }        tmp = end*end;        if(tmp > x)            return end-1;        else            return end;    }


   為了方便理解,就先以本題為例:

迭代公式,程式就好寫了。關於牛頓迭代法,可以參考以及。

int sqrt(int x) {// Start typing your C/C++ solution below        // DO NOT write int main() function        if (x ==0)            return 0;        double pre;        double cur = 1;        do        {            pre = cur;            cur = x / (2 * pre) + pre / 2.0;        } while (abs(cur - pre) > 0.00001);        return int(cur);    }




float InvSqrt(float x){    float xhalf = 0.5f*x;    int i = *(int*)&x; // get bits for floating VALUE    i = 0x5f375a86- (i>>1); // gives initial guess y0    x = *(float*)&i; // convert bits BACK to float    x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy    return 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.