[英]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: 我想在以下情况下用Java编写一个函数,该函数接收参数并返回1或0:
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. 如果数组的长度为奇数,则如果奇数之和大于偶数之和,则返回1,否则返回0。
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. 如果数组的长度是偶数,请检查小于或等于10的最大数字。如果是奇数,则返回1。如果是偶数,则返回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. 第一个数组返回1,因为那里的13(odd) + 7(odd)
= 20大于4 + 2 + 8
=14。第二个数组返回0,因为那里的11, 7
是奇数,但是10大于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. 这是一个Java函数,可以满足您的需求。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.