Implement
int sqrt(int x).Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4 Output: 2
Example 2:
Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
1 class Solution { 2 public: 3 int mySqrt(int x) { 4 if (x <=1) return x; 5 int low = 0; 6 int high = x ; 7 while(low <= high) { 8 int mid = low + (high-low)/2; 9 if (x/mid > mid) { 10 low = mid + 1; 11 } else if(x/mid < mid) { 12 high = mid - 1; 13 } else { 14 return mid; 15 } 16 } 17 // 正常二分法,如果没找到,返回的是大于target 的位置。此题需要返回小于target的位置。8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。 18 return low - 1; 19 } 20 };