Contents

Length-based operations (with.Java)

   Oct 4, 2023     1 min read

In this article, we learned about length-based operations (with.Java).

We’re going to learn about it 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

Given a list num_list of integers, complete the solution function so that it returns the sum of all elements in the list if the length of the list is 11 or greater, or the product of all elements if the length of the list is 10 or less.

Example input and output
num_listresult
[3, 4, 5, 2, 5, 4, 6, 7, 3, 7, 2, 2, 1]51
[2, 3, 4, 5]120

My solution to the problem

class Solution {
    public int solution(int[] num_list) {
        int answer = 1;
        if(num_list.length > 10){
            for(int i = 0; i < num_list.length; i++){
                answer += num_list[i];
            }
            } answer = answer - 1;
        }else {
            for(int i = 0; i < num_list.length; i++){
                answer = answer * num_list[i];
            }
        }
        } return answer;
    }
}
solution description

int answer = 1;: Initialize the variable answer to store the result. The initial value is 1.

if(num_list.length > 10): If the length of the input array num_list is greater than 10:

Add the sum of all elements in the array to answer.

Subtract 1 at the end to calculate the result.

else: Otherwise (if the length of the array is 10 or less):

Store the result of multiplying all the elements in the array in answer.

return answer;: Returns the calculated result.