Contents

Number to come next (with.Java)

   May 29, 2024     2 min read

This is an article looking at the “Next Number (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

When an arithmetic sequence or a geometric sequence common is given as a parameter, complete the solution function to return the number that comes after the last element.

Restrictions

  • 2 < length of common < 1,000
  • -1,000 < element of common < 2,000
  • All elements of common are integers.
  • There is no case where it is not an arithmetic sequence or a geometric sequence.
  • In the case of a geometric sequence, the common ratio is an integer other than 0.

Input/Output Example

commonresult
[1, 2, 3, 4]5
[2, 4, 8]16

My solution to the problem

class Solution {
 public int solution(int[] common) {
 int answer = 0;
 if(common[1] - common[0] == common[2] - common[1]){
 answer = common[common.length - 1] + (common[1] - common[0]);
 }else{
 answer = common[common.length - 1] * (common[1] / common[0]);
 }
 return answer;
 }
}

Solution review

This is a function that determines whether it is an arithmetic sequence or an arithmetic sequence and calculates the next term.

Checks whether the values ​​corresponding to indices 0, 1, and 2 of a given array form an arithmetic or geometric sequence.

If it is an arithmetic sequence, the next term is obtained by adding (the arithmetic value) to the last element of the array.

If it is a geometric sequence, multiply the last element of the array by (the value of the common ratio) to get the next term.

Returns the obtained value.