Leetcode: Sqrt (x)

Source: Internet
Author: User

.

I'm so happy. Let's just take two points. However, it should be noted that the use of long is cross-border TM, and the use of unsigned long. Finally, check the returned value.

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;    }


For ease of understanding, let's take this question as an example:

Iteration formulaThe program is easy to write. For more information about the Newton Iteration Method, see.

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;}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.