comments | difficulty | edit_url | tags | ||
---|---|---|---|---|---|
true |
Easy |
|
Given a non-negative integer x
, return the square root of x
rounded down to the nearest integer. The returned integer should be non-negative as well.
You must not use any built-in exponent function or operator.
- For example, do not use
pow(x, 0.5)
in c++ orx ** 0.5
in python.
Example 1:
Input: x = 4 Output: 2 Explanation: The square root of 4 is 2, so we return 2.
Example 2:
Input: x = 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
Constraints:
0 <= x <= 231 - 1
We define the left boundary of the binary search as
In each step of the search, we find the middle value
After the search ends, we return
The time complexity is
class Solution:
def mySqrt(self, x: int) -> int:
l, r = 0, x
while l < r:
mid = (l + r + 1) >> 1
if mid > x // mid:
r = mid - 1
else:
l = mid
return l
class Solution {
public int mySqrt(int x) {
int l = 0, r = x;
while (l < r) {
int mid = (l + r + 1) >>> 1;
if (mid > x / mid) {
r = mid - 1;
} else {
l = mid;
}
}
return l;
}
}
class Solution {
public:
int mySqrt(int x) {
int l = 0, r = x;
while (l < r) {
int mid = (l + r + 1ll) >> 1;
if (mid > x / mid) {
r = mid - 1;
} else {
l = mid;
}
}
return l;
}
};
func mySqrt(x int) int {
return sort.Search(x+1, func(i int) bool { return i*i > x }) - 1
}
impl Solution {
pub fn my_sqrt(x: i32) -> i32 {
let mut l = 0;
let mut r = x;
while l < r {
let mid = (l + r + 1) / 2;
if mid > x / mid {
r = mid - 1;
} else {
l = mid;
}
}
l
}
}
/**
* @param {number} x
* @return {number}
*/
var mySqrt = function (x) {
let [l, r] = [0, x];
while (l < r) {
const mid = (l + r + 1) >> 1;
if (mid > x / mid) {
r = mid - 1;
} else {
l = mid;
}
}
return l;
};
public class Solution {
public int MySqrt(int x) {
int l = 0, r = x;
while (l < r) {
int mid = (l + r + 1) >>> 1;
if (mid > x / mid) {
r = mid - 1;
} else {
l = mid;
}
}
return l;
}
}