Countdown (with.Java)
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_num | end_num | result |
---|---|---|
10 | 3 | [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
System.out.println(result);: Print out the numbers stored in the list.
public static List
List
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.