[LeetCode] Sqrt(x)

69. Sqrt(x)

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.

Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int mySqrt(int x) {
if(!x) return 0;
long long l = 1, r = INT_MAX, res = 0;
while(l <= r) {
long long m = l + (r-l) / 2;
if(m * m <= x) {
res = max(res, m);
l = m + 1;
} else r = m - 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/04/PS/LeetCode/sqrtx/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.