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)