Creating a Collatz Sequence (with.Java)
In this article, we learned how to create a Collatz sequence (with.Java).
We’re going to learn as we go by solving coding test problems, reflecting on the problems we solved, and exploring other ways to solve them. Let’s start with the problem.
Problem
The problem of asking whether, for any natural number x, if the current value is x, if we keep repeating the calculation of dividing by 2 if x is even and replacing it with 3 * x + 1 if x is odd, we will surely end up with x = 1 at some point is called the Collatz problem. And the sequence that records all the numbers we’ve gone through is called the Collatz sequence. We know that for any number less than or equal to 1,000, we will reach 1 at some point. Given an arbitrary positive integer n less than or equal to 1,000, complete the solution function to return the Collatz sequence with initial value n.
Example input and output
n: 10 result: [10, 5, 16, 8, 4, 2, 1]
My solution to the problem
import java.util.*;
class Solution {
public int[] solution(int n) {
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(n);
while(n != 1){
if(n % 2 == 0){
n = n / 2;
} else {
n = 3 * n + 1;
}
temp.add(n);
}
int[] answer = new int[temp.size()];
for(int i = 0; i < temp.size(); i++){
answer[i] = temp.get(i);
}
} return answer;
}
}
Solution
ArrayList