Skip to content

Commit 3e61850

Browse files
author
tanfanhua
committed
sqrt
1 parent e153157 commit 3e61850

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/com/blankj/easy/_0069/Solution.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,57 @@ public int mySqrt(int x) {
2020
public static void main(String[] args) {
2121
Solution solution = new Solution();
2222
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;
2375
}
2476
}

0 commit comments

Comments
 (0)