SQRT (x)

Source: Internet
Author: User

https://leetcode.com/problems/sqrtx/

Implement int sqrt(int x) .

Compute and return the square root of X.

Problem Solving Ideas:

The test instructions of this problem is that the integer nearest to sqrt (x) is calculated, exactly equal to or slightly less than.

The note here is that it cannot be mid*mid and will cross over. So change to X/mid, this should pay attention to exclude mid = = 0 o'clock situation. That is, when Left + right < 2, then x =0 or 1.

How do you need to maintain the value of result? Whenever mid-mid < X is updated, the latest result is changed, because mid is going to the right, and it's definitely going to get bigger.

 Public classSolution { Public intMYSQRT (intx) {if(x = = 0 | | x== 1) {            returnx; }        intleft = 0, right = x, result = 0;  while(Left <=Right ) {            intMid = (left + right)/2; if(Mid = = x/mid) {returnmid; }             if(Mid > x/mid) { Right= Mid-1; }            if(Mid < X/mid) { left= Mid + 1; Result=mid; }        }        returnresult; }}

SQRT (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.