you have been an integer array A of size N.you need to pfint the number with the value closest to zero.if there are multiple elements print the number with greater value.
public class Main {
public static void main(String[] args) {
int[] A = {-2, 5, 2, -1, 3, -4, 1, -5};
int closest = Integer.MAX_VALUE;
for (int i = 0; i < A.length; i++) {
if (Math.abs(A[i]) < Math.abs(closest)) {
closest = A[i];
} else if (Math.abs(A[i]) == Math.abs(closest) && A[i] > closest) {
closest = A[i];
}
}
System.out.println(closest);
}
}
Comments
Leave a comment