Contents

Odd vs Even (with.Java)

   Sep 30, 2023     2 min read

In this article, we learned about odd vs. even numbers (with.Java).

We’ll do this by solving a coding test problem, reflecting on the problem we solved, and exploring other ways to solve it.

Let’s start with the problem

Problem

You are given a list of integers, num_list.

Complete the solution function so that it returns the greater of the sum of the odd-numbered elements and the sum of the even-numbered elements, where the first element is called element 1.

If the two values are equal, return that value.

Example input and output
num_listresult
[4, 2, 6, 1, 7, 6]17
[-1, 2, 5, 6, 3]8

My solution to the problem

class Solution {
    public int solution(int[] num_list) {
        int answer = 0;
        int oddSum = 0;
        int evenSum = 0;
        for(int i = 0; i < num_list.length; i++){
            if(i % 2 == 0){
                evenSum += num_list[i];
            }else {
                oddSum += num_list[i];
            }
        }
        } answer = evenSum >= oddSum ? evenSum : oddSum;
        return answer;
    }
}
solution description

int answer = 0;: Initialize the variable answer to store the result.

int oddSum = 0;, int evenSum = 0;: Initialize variables oddSum and evenSum to sum the elements at even and odd indices.

for(int i = 0; i < num_list.length; i++) : Iterate over the input array num_list, examining each element.

if(i % 2 == 0) : If the current index i is an even number:

Add the current element value to evenSum.

else : If the current index i is odd:

Add the current element value to oddSum.

answer = evenSum >= oddSum ? evenSum : oddSum;: Compare the sum of the elements at the even index, evenSum, and the sum of the elements at the odd index, oddSum, and store the larger sum in answer.

return answer;: Finally returns the larger of the two sums.