How do I find the largest negative value in an array with both positive and negative values?

前端 未结 7 1301
無奈伤痛
無奈伤痛 2021-01-29 15:43

I need to return the greatest negative value, and if there are no negative values, I need to return zero. Here is what I have:

public int greatestNegative(int[]          


        
7条回答
  •  难免孤独
    2021-01-29 16:22

    Please check following code, which will first calculate small number from array, then check is it positive? if yes return 0 else return negative.

    public static int greatestNegative(int[] list) 
    {
        int negativeNumbers = Integer.MAX_VALUE;
        for (int i = 0; i < list.length; i++) {
            if (list[i] < negativeNumbers)
                    negativeNumbers  = list[i];
        }
    
        if(negativeNumbers  >=0)
             return 0;
        else
             return negativeNumbers;
    
    }
    

提交回复
热议问题