Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding closest number to 0

Tags:

java

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 );    
    }    
}
like image 482
user3172930 Avatar asked May 20 '14 13:05

user3172930


People also ask

How do I find the nearest number to 0?

The distance from 1 to 0 is |1| = 1. The distance from 4 to 0 is |4| = 4. The distance from 8 to 0 is |8| = 8. Thus, the closest number to 0 in the array is 1.

Which number is the biggest closest to zero?

Using this rule, 2.8 is the largest of the two positive numbers. For negative numbers, it's opposite of positive numbers. Rule # 3 says with negative numbers, the integer closest to zero is of greater value. For the two negative integers, if I draw a line from zero to each of them, -1.2 is closest to zero.


3 Answers

This will do it in O(n) time:

int[] arr = {1,4,5,6,7,-1};

int closestIndex = 0;
int diff = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; ++i) {
    int abs = Math.abs(arr[i]);
    if (abs < diff) {
        closestIndex = i;
        diff = abs;
    } else if (abs == diff && arr[i] > 0 && arr[closestIndex] < 0) {
        //same distance to zero but positive 
        closestIndex =i;
    }
}   
System.out.println(arr[closestIndex ]);
like image 77
kmera Avatar answered Oct 01 '22 03:10

kmera


Just add zero to this list.

Then sort the list

Arrays.sort(data);

then grab the number before or after the zero and pick the minimum one greater than zero

like image 25
Bachmann Avatar answered Oct 01 '22 03:10

Bachmann


If you are using java8:

import static java.lang.Math.abs;
import static java.lang.Math.max;

public class CloseToZero {
    public static void main(String[] args) {
        int[] str = {2,3,-2};
        Arrays.stream(str).filter(i -> i != 0)
                .reduce((a, b) -> abs(a) < abs(b) ? a : (abs(a) == abs(b) ? max(a, b) : b))
                .ifPresent(System.out::println);
    }
}
like image 43
M. Abbas Avatar answered Oct 01 '22 01:10

M. Abbas