포스트

콜라츠 수열 만들기

https://school.programmers.co.kr/learn/courses/30/lessons/181919

문제

  • 문제 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<Integer> solution(int n) {
        List<Integer> result = new ArrayList<>();
        result.add(n); // 초기값 추가
        
        while (n != 1) {
            if (n % 2 == 0) { // 짝수인 경우
                n /= 2;
            } else { // 홀수인 경우
                n = 3 * n + 1;
            }
            result.add(n); // 변환된 값 추가
        }
        
        return result;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        List<Integer> result = sol.solution(10);
        System.out.println(result); // 출력: [10, 5, 16, 8, 4, 2, 1]
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Solution {
    public int[] solution(int n) {
        // 콜라츠 수열의 최대 길이는 1000을 넘지 않으므로 크기가 1000인 배열을 생성한다.
        int[] result = new int[1000];
        int index = 0;
        result[index++] = n; // 초기값 추가
        
        while (n != 1) {
            if (n % 2 == 0) { // 짝수인 경우
                n /= 2;
            } else { // 홀수인 경우
                n = 3 * n + 1;
            }
            result[index++] = n; // 변환된 값 추가
        }
        
        // 결과 배열의 크기를 콜라츠 수열의 실제 길이에 맞게 조정한다.
        int[] finalResult = new int[index];
        System.arraycopy(result, 0, finalResult, 0, index);
        return finalResult;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] result = sol.solution(10);
        for (int num : result) {
            System.out.print(num + " "); // 출력: 10 5 16 8 4 2 1
        }
        System.out.println();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Integer> solution(int n) {
        List<Integer> collatzSequence = new ArrayList<>();
        collatzSequence.add(n);

        while (n != 1) { // n으로부터 시작해서 콜라츠 추측에 따라 계산하여 수열을 만들어낸다.
            if (n % 2 == 0) {
                n /= 2;
            } else {
                n = 3 * n + 1;
            }
            collatzSequence.add(n);
        }

        return collatzSequence; // 결과는 List<Integer> 형태로 반환된다.
    }
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.