forked from TonnyL/Windary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SqrtX.js
79 lines (68 loc) · 1.34 KB
/
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Implement int sqrt(int x).
* Compute and return the square root of x.
*
* Accepted.
*/
/**
* @param {number} x
* @return {number}
*/
let mySqrt = function (x) {
// A tricky way to solve the problem.
// return parseInt(Math.sqrt(x));
if (x <= 0) {
return 0;
}
if (x <= 3) {
return 1;
}
let high = parseInt(x / 2), low = 1;
// To avoid overflow.
if (x >= 46340 * 46340) {
return 46340;
}
if (high > 46340) {
high = 46340;
}
let mid = parseInt((high + 1) / 2);
do {
if (mid * mid > x) {
high = mid - 1;
} else if (mid * mid < x) {
if ((mid + 1) * (mid + 1) > x) {
return mid;
}
low = mid + 1;
} else {
return mid;
}
mid = parseInt((low + high) / 2);
} while (high > low);
return mid;
};
if (mySqrt(0) === 0) {
console.log("pass")
} else {
console.error("failed")
}
if (mySqrt(1) === 1) {
console.log("pass")
} else {
console.error("failed")
}
if (mySqrt(2147395599) === 46339) {
console.log("pass")
} else {
console.error("failed")
}
if (mySqrt(2147395600) === 46340) {
console.log("pass")
} else {
console.error("failed")
}
if (mySqrt(6) === 2) {
console.log("pass")
} else {
console.error("failed")
}