Skip to content

Commit 7026727

Browse files
committed
rewrite
1 parent 16f5dd8 commit 7026727

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

Sqrtx.java

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
2-
31
/**
42
* Implement int sqrt(int x).
53
*
@@ -8,12 +6,21 @@
86

97
public class Sqrtx {
108
public int sqrt(int x) {
11-
double x0 = x / 2.0;
12-
double x1 = (x0 + x / x0) / 2.0;
13-
while (Math.abs(x1 - x0) > 0.00001) {
14-
x0 = x1;
15-
x1 = (x0 + x / x0) / 2.0;
16-
}
17-
return (int) x1;
18-
}
9+
if (x == 0 || x == 1) return x;
10+
long low = 1;
11+
long high = x;
12+
long mid = 0;
13+
while (low <= high) {
14+
mid = (low + high) / 2;
15+
if (mid * mid <= x && (mid + 1) * (mid + 1) > x) {
16+
break;
17+
}
18+
if (mid * mid > x) {
19+
high = mid - 1;
20+
} else {
21+
low = mid + 1;
22+
}
23+
}
24+
return new Long(mid).intValue();
25+
}
1926
}

0 commit comments

Comments
 (0)