File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed
Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change 1+ package Leetcode .Youtube ;
2+
3+ public class SquareRootX {
4+
5+ public static int mySqrt (int x ) {
6+
7+ for (int i = 0 ; i <= x ; i ++) {
8+
9+ if (i * i == x )
10+ return i ;
11+
12+ if (i * i > x ) {
13+ return i - 1 ;
14+ }
15+ }
16+
17+ return -1 ;
18+ }
19+
20+ // optimal approach using binary search
21+ public static int mySqrt2 (int x ) {
22+ if (x < 2 )
23+ return x ;
24+
25+ long low = 1 , high = x / 2 ;
26+ long ans = 0 ;
27+
28+ while (low <= high ) {
29+
30+ long mid = low + (high - low ) / 2 ;
31+
32+ if (mid * mid <= x ) {
33+ ans = mid ;
34+ low = mid + 1 ;
35+ } else {
36+ high = mid - 1 ;
37+ }
38+ }
39+
40+ return (int )ans ;
41+ }
42+
43+ public static void main (String [] args ) {
44+
45+ System .out .println (mySqrt (4 ));
46+ System .out .println (mySqrt (8 ));
47+ System .out .println (mySqrt (2 ));
48+ System .out .println (mySqrt (67 ));
49+ System .out .println (mySqrt (86 ));
50+ System .out .println (mySqrt (40 ));
51+ System .out .println (mySqrt (999999999 ));
52+
53+ System .out .println ();
54+
55+ System .out .println (mySqrt2 (4 ));
56+ System .out .println (mySqrt2 (8 ));
57+ System .out .println (mySqrt2 (2 ));
58+ System .out .println (mySqrt2 (67 ));
59+ System .out .println (mySqrt2 (86 ));
60+ System .out .println (mySqrt2 (40 ));
61+ System .out .println (mySqrt2 (999999999 ));
62+ }
63+ }
You can’t perform that action at this time.
0 commit comments