Skip to content

Commit bcb6eca

Browse files
committed
二分法处理
1 parent fa60958 commit bcb6eca

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

code/LeetCode/src/Sqrt.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,36 @@ public static int mySqrt(int x) {
3939
return (int)y;
4040
}
4141

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+
4265
public static void main(String[] args) {
4366
int input1 = 4;
4467
System.out.println("input: " +input1+ " sqrt: " + mySqrt(input1));
68+
System.out.println("input: " +input1+ " mySqrtWithMid: " + mySqrtWithMid(input1));
4569

4670
int input2 = 8;
4771
System.out.println("input: " +input2+ " sqrt: " + mySqrt(input2));
72+
System.out.println("input: " +input2+ " mySqrtWithMid: " + mySqrtWithMid(input2));
4873
}
4974
}

0 commit comments

Comments
 (0)