forked from JadeZYX/Java_LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP0069Sqrt.java
More file actions
55 lines (55 loc) · 1.2 KB
/
Copy pathP0069Sqrt.java
File metadata and controls
55 lines (55 loc) · 1.2 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class P0069Sqrt {
public int mySqrt(int x){
if(x<=1)return x;
int left=1;
int right=x;
int res=-1;
while(left<right){
int mid=left+(right-left)/2;
double product=1.0*mid*mid;
if(product==x){
return mid;
}
else if(product>x){
right=mid;
}
else{
res=mid;//记录当前接近答案的值
left=mid+1;
}
}
return res;
}
public int mySqrt1(int x){//bf
if(x<=1)return x;
if(x==2)return 1;
int i=1;
while(i<x){
double product=1.0*i*i;
if(product==x){
return i;
}
else if(product>x){
return i-1;
}
i++;
}
return 1;
}
public int mySqrt2(int x) {
if(x==0)return 0;
int res=1;
for(int i=1;i<x;i++){
double product=1.0*i*i;
if(product<=x){
res=i;
}
else{
break;
}
}
return res;
}
}
//P0069Sqrt p69=new P0069Sqrt();
//System.out.println(p69.mySqrt(2147483646));