Contents

Countdown (with.Java)

   Sep 20, 2023     2 min read

In this article, About Countdown (with.Java)

We’re going to take a look at solving a coding test problem, provide a retrospective on the problem we solved, and explore other ways to solve it.

Let’s start with the problem

Problem

Given integers start_num and end_num, complete the solution function so that it returns a list of numbers decrementing by 1 from start_num to end_num.

Example input and output
start_numend_numresult
103[10, 9, 8, 7, 6, 5, 4, 3]

My solution to the problem

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public static void main(String[] args) {
        int start_num = 10;
        int end_num = 5;
        List<Integer> result = solution(start_num, end_num);
        System.out.println(result);
    }

    } public static List<Integer> solution(int start_num, int end_num) {
        List<Integer> result = new ArrayList<>();

        for (int i = start_num; i >= end_num; i--) {
            result.add(i);
        }

        } return result;
    }
}

Solution

int start_num = 10; and int end_num = 5;: initialize the starting number start_num to 10 and the ending number end_num to 5.

List result = solution(start_num, end_num);: Call the solution function to store the numbers from the start number to the end number in a list, and assign them to the result variable.

System.out.println(result);: Print out the numbers stored in the list.

public static List solution(int start_num, int end_num) : The solution function takes as input the starting number start_num and the ending number end_num, and returns a list containing the numbers from the starting number to the ending number.

List result = new ArrayList<>(); : Create an integer list result to store the result.

for (int i = start_num; i >= end_num; i–) : Executes a decrementing iteration from the start number to the end number.

result.add(i);: Add each number i to the list result.

return result;: Returns the list result, which contains the numbers from the start number to the end number.

This code stores the numbers from the start number to the end number in a list in reverse order, and outputs the list.