Given a list of interagers. determine whether the sum if its elements is odd or even. Give your answer as a string matching 'odd' or 'even'.
If the input array is empty consider it as: [0] (array with a zero).
Example:
Input [0]:
Output: ''even"
Input [0, 1, 4]
Output: "odd"
我的解法:
function oddOrEven(arr = []) {
var diff = Math.abs(sum) % 2;
var typeMap = {
0: 'even',
1: 'odd',
};
return typeMap[diff];
}
简短优解
解法1:
function oddOrEven(arr) {
return arr.reduce((a, b) => a + b, 0) % 2 ? 'odd' : 'even';
}
解法2:
function oddOrEven(arr) {
return ['even', 'odd'][Math.abs(arr.reduce((acc, cur) => acc + cur, 0)) % 2];
}