File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
src/com/blankj/easy/_0069 Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change @@ -20,5 +20,57 @@ public int mySqrt(int x) {
20
20
public static void main (String [] args ) {
21
21
Solution solution = new Solution ();
22
22
System .out .println (solution .mySqrt (10 ));
23
+ System .out .println (solution .sqrt (10 ));
24
+ System .out .println (solution .sqrt2 (10 ));
25
+ System .out .println (solution .mySqrt (4 ));
26
+ System .out .println (solution .sqrt (4 ));
27
+ System .out .println (solution .sqrt2 (4 ));
28
+ System .out .println (solution .mySqrt (3 ));
29
+ System .out .println (solution .sqrt (3 ));
30
+ System .out .println (solution .sqrt2 (3 ));
31
+ System .out .println (solution .mySqrt (100 ));
32
+ System .out .println (solution .sqrt (100 ));
33
+ System .out .println (solution .sqrt2 (100 ));
34
+
35
+ }
36
+
37
+ public int sqrt (int x ) {
38
+ if (x <= 0 ) {
39
+ return 0 ;
40
+ }
41
+ for (int i = 0 ; i < x /2 ; i ++) {
42
+ if (i * i <= x && (i + 1 ) * (i * 1 ) > x ) {
43
+ return i ;
44
+ }
45
+ }
46
+
47
+ return x /2 ;
48
+ }
49
+
50
+ public int sqrt2 (int x ) {
51
+ if (x <= 0 ) {
52
+ return 0 ;
53
+ }
54
+ int low = 0 ;
55
+ int high = x /2 ;
56
+ while (low <= high ) {
57
+ int mid = (low + high ) / 2 ;
58
+ if (mid *mid == x ) {
59
+ return mid ;
60
+ } else if (mid *mid < x ) {
61
+ if (low == mid ) {
62
+ if (high * high > x ) {
63
+ return mid ;
64
+ } else {
65
+ return high ;
66
+ }
67
+ }
68
+ low = mid ;
69
+ } else {
70
+ high = mid ;
71
+ }
72
+ }
73
+
74
+ return -1 ;
23
75
}
24
76
}
You can’t perform that action at this time.
0 commit comments