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

前端 未结 7 1219
無奈伤痛
無奈伤痛 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:29

    Just go about finding the max number with an added condition.

    public static int greatestNegative(int[] list) {
        int max = Integer.MIN;
        boolean set = false;
        for (int i = 0; i < list.length; i++) {
            if (list[i] < 0 && list[i] > max) {
                 max = arr[i];
                 set = true;
            }
        }
        if (!set)
            max = 0;
        return max;
    }
    
    0 讨论(0)
提交回复
热议问题