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

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

    If you need the greatest negative number then sort array thin search for first negative number

    import java.util.Arrays;
    
    class Main {
    
        public static void main(String[] args) {
            int arr[] = { 2, 4, 1, 7,2,-3,5,-20,-4,5,-9};
            System.out.println(greatestNegative(arr));
        }
    
        private static int greatestNegative(int[] arr) {
            Arrays.sort(arr);
            for (int i = arr.length - 1; i >= 0; i--) {
                if (isNegative (arr[i])) {
                    return arr[i];
                }
            }
            return 0;
        }
    
        private static boolean isNegative (int i) {
            return i < 0;
        }
    }
    

    Output : -3

提交回复
热议问题