I am currently studying binary search so I solved this coding challenge:
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. from leetcode https://leetcode.com/problems/sqrtx/
I used the following code, but I don't understand why in some cases I have to return sqrt-1, and in some other cases just sqrt.
var mySqrt = function(x) {
let min = 0;
let max = x;
let sqrt;
while(min<=max){
sqrt = Math.floor((min+max)/2);
if(sqrt*sqrt == x ){
return Math.floor(sqrt);
} else if(sqrt*sqrt < x){
min = sqrt + 1;
} else max = sqrt - 1;
}
return sqrt*sqrt > x ? sqrt-1: sqrt;
};