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)