69. Sqrt(x)(二分查找)
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.
class Solution { public: int mySqrt(int x) { if (x<=1) return x; int low = 0,high = x; while(low < high) { int mid = low + (high - low)/2; int aa = x/mid; if (aa<mid) { high = mid; } else if (aa > mid ) { low = mid + 1; } else { return mid; } } // 开区间,打个补丁 if (low>x/low) return low-1; return low; } };
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 };