Even or Odd Array Sum in Java

The challenge

Given a list of numbers, 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).

Example:

odd_or_even([0])          ==  "even"
odd_or_even([0, 1, 4])    ==  "odd"
odd_or_even([0, -1, -5])  ==  "even"

The solution in Java code

Option 1 (using streams):

public class Solution {
  public static String oddOrEven (int[] array) {
    return (java.util.Arrays.stream(array).sum()%2==0) 
      ? "even" : "odd";
  }
}

Option 2 (using forloop):

public class Solution {
  public static String oddOrEven (int[] array) {
    int sum = 0;
    for (int n : array){
      sum += n;
    }
    return sum%2==0 ? "even" : "odd";
  }
}

Option 3 (using xor):

public class Solution {
  public static String oddOrEven (int[] array) {
    int xor = 0;
    for (int i : array){
      xor ^= i;
    }
    return (xor & 1) == 1 ? "odd" : "even";
  }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.util.*;
import java.util.stream.IntStream;

public class SolutionTest {
    @Test
    public void test1() {
       assertEquals("odd", Solution.oddOrEven(new int[] {2, 5, 34, 6}));
       assertEquals("odd", Solution.oddOrEven(new int[] {0, 1, 2}));
       assertEquals("even", Solution.oddOrEven(new int[] {0, 1, 3}));
       assertEquals("even", Solution.oddOrEven(new int[] {1023, 1, 2}));
    }
    
    @Test
    public void randomTests() {
    Random r = new Random();
     for(int j = 1; j <= 200; j++) {
      int length = 1+r.nextInt(10);
      int[] array = new int[length];
        for(int i = 0; i < array.length; i++) {
        int random_number = 1+r.nextInt(2000);
        array[i] = random_number;
        }

        assertEquals(this.n(array), Solution.oddOrEven(array));
    }
  }
}
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments