File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change @@ -39,11 +39,36 @@ public static int mySqrt(int x) {
39
39
return (int )y ;
40
40
}
41
41
42
+ public static int mySqrtWithMid (int x ) {
43
+ if (x < 1 ) {
44
+ return 0 ;
45
+ }
46
+ int left = 0 ;
47
+ int right = x ;
48
+ while (true ) {
49
+ int mid = left + ((right - left ) >> 1 );
50
+ if (mid < 1 ) {
51
+ return 1 ;
52
+ }
53
+ if (mid > x / mid ) {
54
+ right = mid ;
55
+ } else {
56
+ if (mid + 1 > x /(mid + 1 )) {
57
+ return mid ;
58
+ }
59
+
60
+ left = mid + 1 ;
61
+ }
62
+ }
63
+ }
64
+
42
65
public static void main (String [] args ) {
43
66
int input1 = 4 ;
44
67
System .out .println ("input: " +input1 + " sqrt: " + mySqrt (input1 ));
68
+ System .out .println ("input: " +input1 + " mySqrtWithMid: " + mySqrtWithMid (input1 ));
45
69
46
70
int input2 = 8 ;
47
71
System .out .println ("input: " +input2 + " sqrt: " + mySqrt (input2 ));
72
+ System .out .println ("input: " +input2 + " mySqrtWithMid: " + mySqrtWithMid (input2 ));
48
73
}
49
74
}
You can’t perform that action at this time.
0 commit comments