File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ) ;
You can’t perform that action at this time.
0 commit comments