It’s one of the most common Java interview questions !!!

Let’s talk about this post. In this post, we will see how to write a Java program to find the Integer Number in a given array that is closest to zero. Mentioned below is the snippet from a hiring team.

In the question, they stated that we have to implement a method to return the integer number in a given array that is closest to zero. Read carefully they also mentioned that if a number is positive and negative we should pick the positive number.

public static int getClosestToZero(int[] a) {
/*
......
*/
}

Feel Free to Skip. it’s optional. we will loop through the given array and we will check with the first value multiplication. If the array’s value is less than or equal to first value then array’s value will be the closest value.

If your question why need to multiply we can directly compare with our array’s value. but it will give you a negative output. That’s why need to multiply to compare then u will get the positive output.

Solution :

package javatuto;
 
import java.util.Arrays;
 
/**
 *
 * @author marifurr
 */
public class ClosestToZero {
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        int[] testingArray = {4,7,9,2,-2};
        
        int result = getClosestToZero(testingArray);
        
        System.out.println("The Closest Number To Zero in this Array is : " + result);
 
    }
 
    public static int getClosestToZero(int[] a) {
        int currentValue = 0;
        int closestVal = a[0];
        Arrays.sort(a);
 
        for (int index = 0; index < a.length; index++) {
            currentValue = a[index] * a[index];
            if (currentValue <= (closestVal * closestVal)) {
                closestVal = a[index];
            }
        }
        return closestVal;
    }
 
}

Output :

The Closest Number To Zero in this Array is : 2
BUILD SUCCESSFUL (total time: 0 seconds)

Thanks for choosing us from your google search. We appreciate your intention. If you want to cover us some more complex interview questions related to Java, Spring, Hibernate, and SQL. Please let us know in the comment section. we will solve it for you.

Tagged:

Laisser un commentaire