简体   繁体   中英

Find out the odd value and meet criteria in java

I would like to write a function in java that receives a parameter and returns 1 or 0, in the following conditions:

  1. If the length of the array is odd, return 1 if the sum of the odd numbers is greater than the sum of the even numbers, and 0 otherwise.

  2. If the length of the array is even, check the largest number less or equal then 10. If it is odd, return 1. If it is even, return 0.

For example, using the following arrays:

array1 = {13, 4, 7, 2, 8}
array2 = {11, 7, 4, 2, 3, 10}

The first array returns 1, because there 13(odd) + 7(odd) = 20 is greater then 4 + 2 + 8 = 14. The second array returns 0, because there 11, 7 are odd but, 10 is greater then 7.

What I already tried, please check below:

   public static int isOddHeavy(int[] arr) {
        int summationOd = 0;
        int summationEv = 0;

        for (int i = 0; i < arr.length; i++) {
            if (i % 2 != 0) {
                summationOd = sumOddEven(arr);
            } else {
                summationEv = sumOddEven(arr);
            }
        }

        if(summationOd > summationEv) {
            return 1;
        } else {
            return 0;
        }

    }

    public static int sumOddEven(int[] arr) {
        int total = 0;
        for (int i = 1; i < arr.length; i++) {
            total += arr[i];
        }
        return total;
    }

Here is a Java function that does what you want. Just iterate through the array, updating the variables and check your conditions in the end.

    public static int yourFunction(int[] arr) {
        int sumOdd = 0;
        int sumEven = 0;
        int maxOdd = 0;
        int maxEven = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 == 0) {
                sumEven += arr[i];
                if (maxEven < arr[i] && arr[i] <= 10)
                    maxEven = arr[i];
            }
            else {
                sumOdd += arr[i];
                if (maxOdd < arr[i] && arr[i] <= 10)
                    maxOdd = arr[i];
            }
        }
        if (arr.length%2 != 0)
            return (sumOdd > sumEven) ? 1 : 0;
        return (maxOdd > maxEven) ? 1 : 0;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM