Skip to content

Commit 9b37c0a

Browse files
committed
add solution of problem 69: sqrt(x)
1 parent e447e71 commit 9b37c0a

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

Sqrt(x)69/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Implement `int sqrt(int x)`.
2+
3+
Compute and return the square root of *x*.

Sqrt(x)69/Solution.java

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

0 commit comments

Comments
 (0)