-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClosestToZero.java
More file actions
29 lines (29 loc) · 874 Bytes
/
ClosestToZero.java
File metadata and controls
29 lines (29 loc) · 874 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
public class ClosestToZero {
public int findClosestNumber(int[] nums) {
int closest=nums[0];
for(int x:nums) {
if (Math.abs(x)<Math.abs(closest)) {
closest=x;
}
}
if (closest<0&&contains(nums,Math.abs(closest))) {
return Math.abs(closest);
}
else {
return closest;
}
}
public boolean contains(int[] arr,int tar) {
for (int i : arr) {
if (i==tar) {
return true;
}
}
return false;
}
public static void main(String[] args) {
ClosestToZero obj=new ClosestToZero();
int[] arr={-1,3,-2};
System.out.println(obj.findClosestNumber(arr));
}
}