Skip to content

Finding closest number to 0

I am trying to troubleshoot a program in Java.

Requirements: Need to find the closest value to zero in an Array. In the Array if the values are like 1 and -1 the closest should be the positive value.

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 );    
    }    
}

Answer

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 );
    }
}