Sqrt(x)
Input:
4
Output:
2Input:
8
Output:
2
Explanation:
The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.Analysis
Binary Search
Solution
Last updated
Input:
4
Output:
2Input:
8
Output:
2
Explanation:
The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.Last updated
public int mySqrt(int x) {
long r = x;
while (r*r > x)
r = (r + x/r) / 2;
return (int) r;
}public int mySqrt(int x) {
int left = 1, right = x;
while (left <= right) {
int mid = left + (right - left) / 2;
if (mid == x / mid) {
return mid;
} else if (mid < x / mid) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return right;
}