Original title link:
https://leetcode-cn.com/problems/sqrtx/
topic:
Achieve int sqrt (int x) function.
Computes and returns the square root of x, where x is a non-negative integer.
Since the return type is an integer, the integer part of the result to retain only the fractional part is rounded down.
Example 1:
Input: 4 Output: 2
Example 2:
Input: 8 Output: 2 Description: 8 square root is 2.82842 ..., since the return type is an integer, the fractional part is rounded down.
Ideas:
Use binary search.
Because a number of the square of its own, and certainly not more than a maximum of no more than half of it, it is judged that the condition can be written ≤ x for the mid ². Since there may be written bounds case, the determination condition may be written as mid ≤ x / mid.
Code:
int mySqrt(int x){ int l = 0, r = x; while(l < r) { int mid = (long long)l + r + 1 >> 1; if(mid <= x / mid) l = mid; else r = mid - 1; } return l; }