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)