We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 16f5dd8 commit 7026727Copy full SHA for 7026727
Sqrtx.java
@@ -1,5 +1,3 @@
1
-
2
3
/**
4
* Implement int sqrt(int x).
5
*
@@ -8,12 +6,21 @@
8
6
9
7
public class Sqrtx {
10
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
+ if (x == 0 || x == 1) return x;
+ long low = 1;
+ long high = x;
+ long mid = 0;
+ while (low <= high) {
+ mid = (low + high) / 2;
+ if (mid * mid <= x && (mid + 1) * (mid + 1) > x) {
+ break;
+ }
+ if (mid * mid > x) {
19
+ high = mid - 1;
20
+ } else {
21
+ low = mid + 1;
22
23
24
+ return new Long(mid).intValue();
25
26
}
0 commit comments