Java 寻找最接近 0 的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23760979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:04:55  来源:igfitidea点击:

Finding closest number to 0

java

提问by user3172930

I am trying to troubleshoot a program in Java.

我正在尝试对 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.

要求:需要在数组中找到最接近零的值。在数组中,如果值类似于 1 和 -1,则最接近的应该是正值。

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

采纳答案by JuanZe

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.

对数组进行排序(添加一行代码),如果为具有相同距离的正数和负数选择相同的绝对值,则您选择的最后一个数字将为正数。

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

回答by lpratlong

As you multiply data[i] with data[i], a value negative and a value positive will have the same impact. For example, in your example: 2 and -2 will be 4. So, your code is not able to sort as you need.

当您将 data[i] 与 data[i] 相乘时,负值和正值将产生相同的影响。例如,在您的示例中:2 和 -2 将是 4。因此,您的代码无法根据需要进行排序。

So, here, it takes -2 as the near value since it has the same "weight" as 2.

因此,在这里,它采用 -2 作为接近值,因为它具有与 2 相同的“权重”。

回答by Bachmann

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

然后抓住零之前或之后的数字并选择大于零的最小数字

回答by munyul

Assumption is that the array datahas at least 1 value.

假设数组data至少有 1 个值。

int closedToZero = 0;
for ( int i = 1; i < data.length; i++ )
{
    if ( Math.abs(data[i]) < Math.abs(data[closedToZero]) ) closedToZero = i;
}

The value in closedToZerois the index of the closed to zero, not the value.

中的值closedToZero是闭于零的索引,而不是值。

回答by kmera

This will do it in O(n)time:

这将O(n)及时做到:

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

回答by M. Abbas

If you are using java8:

如果您使用的是 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);
    }
}

回答by Anass Gandalf

here is a method that gives you the nearest to zero.

这是一种方法,可以为您提供最接近零的方法。

  • use case 1 : {1,3,-2} ==> return 1 : use the Math.abs() for comparison and get the least.
  • use case 2 : {2,3,-2} ==> return 2 : use the Math.abs() for comparison and get the Math.abs(least)
  • use case 3 : {-2,3,-2} ==> return -2: use the Math.abs() for comparison and get the least.

    public static double getClosestToZero(double[] liste) {
    // if the list is empty return 0
    if (liste.length != 0) {
        double near = liste[0];
        for (int i = 0; i < liste.length; i++) {
            // here we are using Math.abs to manage the negative and
            // positive number
            if (Math.abs(liste[i]) <= Math.abs(near)) {
                // manage the case when we have two equal neagative numbers
                if (liste[i] == -near) {
                    near = Math.abs(liste[i]);
                } else {
                    near = liste[i];
                }
            }
        }
        return near;
    } else {
        return 0;
    }
    

    }

  • 用例 1 : {1,3,-2} ==> return 1 : 使用 Math.abs() 进行比较并得到最少的。
  • 用例 2 : {2,3,-2} ==> return 2 : 使用 Math.abs() 进行比较并获得 Math.abs(least)
  • 用例 3 : {-2,3,-2} ==> return -2: 使用 Math.abs() 进行比较并得到最少的。

    public static double getClosestToZero(double[] liste) {
    // if the list is empty return 0
    if (liste.length != 0) {
        double near = liste[0];
        for (int i = 0; i < liste.length; i++) {
            // here we are using Math.abs to manage the negative and
            // positive number
            if (Math.abs(liste[i]) <= Math.abs(near)) {
                // manage the case when we have two equal neagative numbers
                if (liste[i] == -near) {
                    near = Math.abs(liste[i]);
                } else {
                    near = liste[i];
                }
            }
        }
        return near;
    } else {
        return 0;
    }
    

    }

回答by Cristian Babarusi

You can do like this:

你可以这样做:

String res = "";

        Arrays.sort(arr);
        int num = arr[0];
        int ClosestValue = 0;

        for (int i = 0; i < arr.length; i++)
        {
            //for negatives
            if (arr[i] < ClosestValue && arr[i] > num)
            num = arr[i];
            //for positives
            if (arr[i] > ClosestValue && num < ClosestValue)
            num = arr[i];
        }
        res = num;

        System.out.println(res);

First of all you need to store all your numbers into an array. After that sort the array --> that's the trick who will make you don't use Math.abs(). Now is time to make a loop that iterates through the array. Knowing that array is sorted is important that you start to make first an IF statement for negatives numbers then for the positives (in this way if you will have two values closest to zero, let suppose -1 and 1 --> will print the positive one).

首先,您需要将所有数字存储到一个数组中。在对数组进行排序之后 --> 这就是使您不使用 Math.abs() 的技巧。现在是创建一个遍历数组的循环的时候了。知道数组已排序很重要,您开始首先为负数创建 IF 语句,然后为正数(通过这种方式,如果您将有两个最接近零的值,假设 -1 和 1 --> 将打印正数一)。

Hope this will help you.

希望这会帮助你。

回答by DevDisrupt

The easiest way to deal with this is split the array into positive and negative sort and push the first two items from both the arrays into another array. Have fun!

解决这个问题的最简单方法是将数组拆分为正排序和负排序,并将两个数组中的前两项推送到另一个数组中。玩得开心!

function closeToZeroTwo(arr){
let arrNeg = arr.filter(x => x < 0).sort();
let arrPos = arr.filter(x => x > 0).sort();
let retArr = []; 
retArr.push(arrNeg[0], arrPos[0]);
console.log(retArr)
}

回答by bawa

Easiest way to just sort that array in ascending order suppose input is like :

以升序对该数组进行排序的最简单方法假设输入如下:

int[] array = {10,-5,5,2,7,-4,28,65,95,85,12,45};

then after sorting it will gives output like:

然后在排序后它会给出如下输出:

{-5,-4,2,5,7,10,12,28,45,65,85,95,}

and for positive integer number, the Closest Positive number is: 2

对于正整数,最近的正数是:2

Logic :

逻辑:

public class Closest {

public static int getClosestToZero(int[] a) {

    int temp=0;
    //following for is used for sorting an array in ascending nubmer
    for (int i = 0; i < a.length-1; i++) {
        for (int j = 0; j < a.length-i-1; j++) {
            if (a[j]>a[j+1]) {
                temp = a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
            }
        }
    }
    //to check sorted array with negative & positive  values
    System.out.print("{");
    for(int number:a)
        System.out.print(number + ",");

    System.out.print("}\n");
    //logic for check closest positive and Integer
    for (int i = 0; i < a.length; i++) {
        if (a[i]<0 && a[i+1]>0) {
            temp = a[i+1];
        }
    } 
    return temp;
}

  public static void main(String[] args) {
    int[] array = {10,-5,5,2,7,-4,28,65,95,85,12,45};
    int closets =getClosestToZero(array);
    System.out.println("The Closest Positive number is : "+closets);
  }

}