Skip to content

Commit ca42283

Browse files
author
Li Li
committed
add code of 69
1 parent c1117f1 commit ca42283

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Binary search
2+
public class Solution {
3+
public int MySqrt(int x) {
4+
if (x == 0) return 0;
5+
int left = 1, right = x;
6+
while (left + 1 < right) {
7+
int mid = left + (right - left) / 2;
8+
if (mid == x / mid) {
9+
return mid;
10+
} else if (mid > x / mid) {
11+
right = mid;
12+
} else {
13+
left = mid;
14+
}
15+
}
16+
if (right <= x / right) return right;
17+
return left;
18+
}
19+
}
20+
21+
// NewTon
22+
public class Solution {
23+
public int MySqrt(int x) {
24+
if (x == 0) return 0;
25+
long r = x;
26+
while (r * r > x) {
27+
r = (r + x / r) / 2;
28+
}
29+
return (int)r;
30+
}
31+
}

0 commit comments

Comments
 (0)