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.
Example 1:
Input: x = 4 Output: 2
Example 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.
Constraints:
0 <= x <= 231 - 1
Binary search.
class Solution:
def mySqrt(self, x: int) -> int:
left, right = 0, x
while left < right:
mid = (left + right + 1) >> 1
# mid*mid <= x
if mid <= x // mid:
left = mid
else:
right = mid - 1
return left
class Solution {
public int mySqrt(int x) {
int left = 0, right = x;
while (left < right) {
int mid = (left + right + 1) >>> 1;
if (mid <= x /mid) {
// mid*mid <= x
left = mid;
} else {
right = mid - 1;
}
}
return left;
}
}
class Solution {
public:
int mySqrt(int x) {
long long left = 0, right = x;
while (left < right)
{
long long mid = left + ((right - left + 1) >> 1);
if (mid <= x / mid) left = mid;
else right = mid - 1;
}
return (int) left;
}
};
func mySqrt(x int) int {
left, right := 0, x
for left < right {
mid := left + (right-left+1)>>1
if mid <= x/mid {
left = mid
} else {
right = mid - 1
}
}
return left
}
/**
* @param {number} x
* @return {number}
*/
var mySqrt = function (x) {
let left = 0;
let right = x;
while (left < right) {
const mid = (left + right + 1) >>> 1;
if (mid <= x / mid) {
left = mid;
} else {
right = mid - 1;
}
}
return left;
};
public class Solution {
public int MySqrt(int x) {
int left = 0, right = x;
while (left < right)
{
int mid = left + right + 1 >> 1;
if (mid <= x / mid)
{
left = mid;
}
else
{
right = mid - 1;
}
}
return left;
}
}