-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSquareRootV2
More file actions
34 lines (29 loc) · 864 Bytes
/
SquareRootV2
File metadata and controls
34 lines (29 loc) · 864 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
30
31
32
33
34
public class SquareRootV2 {
public int squareRoot (int x){
if ( x < 1){
return 0;
}
int high = x;
int low = 1;
int answer = 1;
while (low<=high){
long mid = low + (high - low) / 2;
if ( mid * mid <=(long)x){
answer = (int) mid;
low = (int) mid + 1;
}else {
high = (int) mid - 1;
}
}
return answer;
}
public static void main(String[] args) {
SquareRootV2 solution = new SquareRootV2();
int x1 = 25;
int sqrt1 = solution.squareRoot(x1);
System.out.println("Square root of " + x1 + " is " + sqrt1);
int x2 = 2;
int sqrt2 = solution.squareRoot(x2);
System.out.println("Square root of " + x2 + " is " + sqrt2);
}
}