Given a non-negative integer x,compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Input: x = 4
Output: 2
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
- 0 <= x <= 2^31 - 1
- java
/*
Success Detail:
Runtime: 1 ms, faster than 100.00% of Java online submissions for Sqrt(x).
Memory Usage: 35.3 MB, less than 91.69% of Java online submissions for Sqrt(x).
*/
class Solution {
public int mySqrt(int x) {
int left = 0, right = x, ans = 0;
while (left <= right) {
int mid = ((right - left) >> 1) + left;
if ((long) mid * mid > x) {
right = mid - 1;
} else {
ans = mid;
left = mid + 1;
}
}
return ans;
}
}