Title Link: Sqrt (x)
Implement int sqrt (int x).
Compute and return the square root of X.
The requirement for this problem is to implement the int sqrt (int x), which is the square root of the computed x.
Consider two points, that is, shillings L and R are 1 and x/2+1 (the square root of x must be less than or equal to x/2+1), then M equals (l+r)/2, and the size of m*m and X is constantly compared.
Due to m*m, it is possible to overflow, so you can use division instead of multiplication, or a long long type.
Complexity of Time: O (LOGN)
Space complexity: O (1)
1 class Solution{2 Public:3 int sqrt(int x) 4 {5 if(x == 0)6 return 0;7 8 int L = 1, R = x / 2 + 1;9 while(L <= R)Ten { One int m = (L + R) / 2; A - if(m <= x / m && m + 1 > x / (m + 1)) - return m; the - if(m > x / m) - R = m - 1; - Else if(m < x / m) + L = m + 1; - } + return L; A } at };
Of course, this problem can also be used as a bitwise operation or Newton method.
Reprint please indicate source: Leetcode---69. SQRT (x)
Leetcode---69. SQRT (x)