-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathSqrt.java
32 lines (32 loc) · 947 Bytes
/
Sqrt.java
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
public class Solution {
public int sqrt(int x) {
// Start typing your Java solution below
// DO NOT write main() function
double pivot = x/2;
int up = (int) pivot;
int down = 0;
while (up >= down){
if (pivot * pivot > x){
if((pivot - 1) * (pivot -1) <= x){
return (int)pivot - 1;
}
up = (int) pivot;
pivot = (up - down )/2;
}
else if (pivot * pivot < x){
if((pivot + 1) * (pivot + 1) > x){
return (int) pivot;
}
if((pivot + 1) * (pivot + 1) == x){
return (int) pivot + 1;
}
down = (int) pivot;
pivot += (up - down)/2;
}
else {
return (int) pivot;
}
}
return down;
}
}