Leetcode Sqrt (x)

Source: Internet
Author: User

Title Description:

Implement int sqrt(int x) .

Compute and return the square root of X.


Title translation: Enter X, return sqrt (x);


C language version:

int mysqrt (int x) {    int T, L, R, Mid;    L = 1;    r = x>>1;    if (x < 2) return x;    while (L <= R) {        mid = (L + r) >> 1;        if (mid = = X/mid) return mid;        else if (Mid < X/mid) {            L = mid + 1;        }        else R = mid-1;    }    return r;}
looks like a simple binary search, in fact, there are a lot of details to note

For example: l initialization problem, formerly habitual initialized to 0, here can not, such as x==2, will appear except 0 error

There are some open squares of the result is a decimal, in this case, the output of an integer, then the last return which value?

At first I was stubborn thought should be the left pointer is small, should return to the left pointer L, the wrong only to find, jump out of the loop

The pointer to the left is already larger than the right hand, so you should return the pointer to the right r!

Leetcode Sqrt (x)

Related Article

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.