forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqrtX.java
More file actions
29 lines (25 loc) · 664 Bytes
/
SqrtX.java
File metadata and controls
29 lines (25 loc) · 664 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package binary_search;
/**
* Created by gouthamvidyapradhan on 22/05/2017.
* Implement int sqrt(int x).
* <p>
* Compute and return the square root of x.
*/
public class SqrtX {
public static void main(String[] args) throws Exception {
System.out.println(new SqrtX().mySqrt(Integer.MAX_VALUE));
}
public int mySqrt(int x) {
int s = 0, e = x;
long ans = 0L;
while (s <= e) {
long m = s + (e - s) / 2;
long prod = m * m;
if (prod <= x) {
s = (int) (m + 1);
ans = m;
} else e = (int) m - 1;
}
return (int) ans;
}
}