给你一个非负整数 x
,计算并返回 x
的 算术平方根 。
由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。
注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5)
或者 x ** 0.5
。
示例 1:
输入:x = 4 输出:2
示例 2:
输入:x = 8 输出:2 解释:8 的算术平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
提示:
0 <= x <= 231 - 1
二分查找。
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;
}
}
impl Solution {
pub fn my_sqrt(x: i32) -> i32 {
if x < 2 {
return x;
}
let mut l = 1;
let mut r = x / 2;
while l < r {
let mid = (l + r + 1) >> 1;
if x / mid < mid {
r = mid - 1
} else {
l = mid;
}
}
l
}
}