Finding closest number to 0
arrays, java
Solution
Sort the array (add one line of code) so the last number you pick up will be positive if the same absolute value is selected for a positive and negative numbers with the same distance.
Source code:
import java.util.Arrays;
public class CloseToZero {
public static void main(String[] args) {
int[] data = {2,3,-2};
int curr = 0;
int near = data[0];
Arrays.sort(data); // add this
System.out.println(Arrays.toString(data));
// find the element nearest to zero
for ( int i=0; i < data.length; i++ ){
System.out.println("dist from " + data[i] + " = " + Math.abs(0 -data[i]));
curr = data[i] * data[i];
if ( curr <= (near * near) ) {
near = data[i];
}
}
System.out.println( near );
}
}
Problem
I have an array of integers, and I need to find the one that's closest to zero (positive integers take priority over negative ones.) Here is the code I have so far: ``` public class CloseToZero { public static void main(String[] args) { int[] data = {2,3,-2}; int curr = 0; int near = data[0]; // find the element nearest to zero for ( int i=0; i < data.length; i++ ){ curr = data[i] * data[i]; if ( curr <= (near * near) ) { near = data[i]; } } System.out.println( near ); } } ``` Currently I'm getting a result of -2 but I should be getting 2. What am I doing wrong?