Sum of consecutive numbers (with.Java)
This is an article about the “Sum of consecutive numbers (with.Java)” problem.
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.
Let’s look at the problem first.
problem
Three consecutive integers that add up to 12 are 3, 4, and 5.
You are given two integers num and total.
Complete the solution function so that when the sum of num consecutive numbers becomes total, it returns an array of integers in ascending order.
Restrictions
- 1 ≤ num ≤ 100
- 0 ≤ total ≤ 1000
- There is no test case in which total cannot be obtained by adding num consecutive numbers.
Input/Output Example
num | total | result |
---|---|---|
3 | 12 | [3, 4, 5] |
5 | 15 | [1, 2, 3, 4, 5] |
4 | 14 | [2, 3, 4, 5] |
5 | 5 | [-1, 0, 1, 2, 3] |
My solution to the problem
class Solution {
public int[] solution(int num, int total) {
int[] answer = new int[num];
int startNum = total / num - (num - 1) / 2;
for(int i = 0; i < num; i++){
answer[i] = startNum++;
}
return answer;
}
}
Solution review
This function generates numbers at regular intervals starting from the starting number, given the sum of the starting number and the total number.
The solution function takes two parameters: num and total.
First, we create an array answer to store the results. The length of this array is set to num.
Initialize the startNum variable to calculate the starting number. This value is calculated by dividing the given total number by the given number and then subtracting (number of numbers - 1) / 2 from that value. This allows numbers to be generated at regular intervals.
Use loops to assign each element a value that starts with a starting number and increases at regular intervals. Returns the result array answer.