[Java] Leetcode69 Sqrt (x)

Source: Internet
Author: User

Implement int sqrt(int x) . Compute and return the square root of X.

Test instructions: Calculates the square root of a number.

Finally think of using binary search to solve the problem, but also spent a little effort, put in eclipse debugging come out. The point is that by multiplying the median value, it is possible to exceed the maximum range of integers, so the comparison will be error-prone. So all definitions are defined as long.

First edition:

public int mysqrt (int. x) {if (x = = 0) return 0;long low = 1;long High = X;long Tmp;long mid = 1;while (Low <= High)//binary lookup {mid = (low + high)/2;tmp = Mid * MID;IF (TMP = = x) return (int) mid;else if (tmp > x) high = Mid-1;else if (tmp < x) Low = mid + 1;} return (int) ((mid*mid) >x?mid-1:mid);}

We can make the above code a little bit better:

public int mysqrt (int x) {Long low = 0;long High = x/2+1;//The value of the square root is found by law not to be greater than its median value of +1. So that each lookup is one less time long tmp;long mid = 1;while (Low <= high) {mid = (low + high)/2;tmp = Mid * MID;IF (TMP = = x) return (int) mi D;else if (tmp > x) high = Mid-1;else if (tmp < x) Low = mid + 1;} return (int) high;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Java] Leetcode69 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.