-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqrtx.js
42 lines (26 loc) · 929 Bytes
/
sqrtx.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* @param {number} x
* @return {number}
*/
var mySqrt = function(x) {
let left = 1;
let right = x;
// The square root of 0 or 1 is itself
if(x < 2)
return x;
// Use binary search to find the square root or the whole number closest to the square root
while(left < right) {
// Find the mid point between left and right
const mid = Math.floor((left + right) / 2)
// Return the mid point if this is the square root
if(mid*mid === x)
return mid;
// If mid squared is greater than x then the answer must be on the left half of mid
else if(mid*mid >x)
right = mid;
// If mid squred is less than x then the answer must be on the right half of mid
else
left = mid+1;
}
return left - 1;
};