get closest value to a number in array

后端 未结 12 1783
庸人自扰
庸人自扰 2020-12-01 07:52

I have an array of positive/negative ints

int[] numbers = new int[10];
numbers[0] = 100;
numbers[1] = -34200;
numbers[2] = 3040;
numbers[3] = 400433;
numbers         


        
12条回答
  •  伪装坚强ぢ
    2020-12-01 08:35

    int myNumber = 490;
    int distance = Math.abs(numbers[0] - myNumber);
    int idx = 0;
    for(int c = 1; c < numbers.length; c++){
        int cdistance = Math.abs(numbers[c] - myNumber);
        if(cdistance < distance){
            idx = c;
            distance = cdistance;
        }
    }
    int theNumber = numbers[idx];
    

    Always initialize your min/max functions with the first element you're considering. Using things like Integer.MAX_VALUE or Integer.MIN_VALUE is a naive way of getting your answer; it doesn't hold up well if you change datatypes later (whoops, MAX_LONG and MAX_INT are very different!) or if you, in the future, want to write a generic min/max method for any datatype.

提交回复
热议问题