Skip to content

Commit 9254515

Browse files
committed
feat: Add efficient binary search solution for square root calculation
1 parent 230f963 commit 9254515

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

easy/sqrtx.test.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// Problem: https://leetcode.com/problems/sqrtx/description/
2+
// Doc: https://leetcode.com/problems/sqrtx/solutions/5491801/efficient-binary-search-for-square-root-calculation/
3+
const mySqrt = (x: number): number => {
4+
let [l, r] = [0, 1];
5+
// We are not allowed to use Math.pow
6+
// So we initialize r using this loop :v
7+
for (let i = 1; i <= 31; i++) {
8+
r *= i;
9+
}
10+
r--;
11+
12+
let ans = 0;
13+
while (l <= r) {
14+
const m = Math.floor((l + r) / 2);
15+
16+
if (m * m === x) return m;
17+
18+
if (m * m > x) {
19+
r = m - 1;
20+
continue;
21+
}
22+
23+
ans = m;
24+
l = m + 1;
25+
}
26+
27+
return ans;
28+
};
29+
30+
describe('Sqrt(x)', () => {
31+
it('should return the square root of x', () => {
32+
expect(mySqrt(0)).toBe(0);
33+
expect(mySqrt(1)).toBe(1);
34+
expect(mySqrt(2)).toBe(1);
35+
expect(mySqrt(4)).toBe(2);
36+
expect(mySqrt(8)).toBe(2);
37+
expect(mySqrt(9)).toBe(3);
38+
expect(mySqrt(16)).toBe(4);
39+
expect(mySqrt(25)).toBe(5);
40+
expect(mySqrt(36)).toBe(6);
41+
expect(mySqrt(49)).toBe(7);
42+
expect(mySqrt(64)).toBe(8);
43+
expect(mySqrt(81)).toBe(9);
44+
expect(mySqrt(100)).toBe(10);
45+
});
46+
});

0 commit comments

Comments
 (0)