Odd or Even?

Lee·2022년 7월 9일

Algorithm

목록 보기
42/92
post-thumbnail

❓ Odd or Even?

Q. Given a list of integers, determine whether the sum of 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).

Examples:
Input: [0]
Output: "even"

Input: [0, 1, 4]
Output: "odd"

Input: [0, -1, -5]
Output: "even"
Have fun!

✔ Solution

//#my solution
function oddOrEven(array) {
  //enter code here
  const result = Math.abs(array.reduce((a, b) => a + b, 0));
  if (result == 0) {
    return "even";
  } else if (result % 2 == 1) {
    return "odd";
  } else if (result % 2 == 0) {
    return "even";
  }
}


//#other solution
function oddOrEven(arr) {
  return arr.reduce((a,b)=>a+b,0) % 2 ? 'odd' : 'even';
}
profile
Lee

0개의 댓글