모든 챌린지
쉬움 1명 해결 정답률 25.0%

Collatz Sequence

Follow the halve-or-triple-and-add-one rule until reaching 1.

배우게 될 내용

  • Follow a rule until a condition is met
  • Count the steps taken
  • Branch on even and odd values

문제

번역본 보기

Start with n. If it is even, divide it by 2; if it is odd, multiply it by 3 and add 1. Repeat until the value is 1. Include both the starting value and the final 1 in your answer.

Implement collatz_sequence(n).

Input

n: The positive starting integer.

Output

Return the complete sequence in order.

제약 조건

1 ≤ n ≤ 10,000. Inputs in this range reach 1 under this rule; all sequence values fit a signed 64-bit integer.

예시

예시 1
입력:
n = 6

예상 출력:
expected = [6, 3, 10, 5, 16, 8, 4, 2, 1]
입력:
long long n = 6;

예상 출력:
std::vector<long long> expected = {6, 3, 10, 5, 16, 8, 4, 2, 1};
입력:
long n = 6;

예상 출력:
long[] expected = new long[] {6, 3, 10, 5, 16, 8, 4, 2, 1};

설명

6 is even, so it becomes 3. Then 3 becomes 10. Continue applying the rule until 1.

예시 2
입력:
n = 1

예상 출력:
expected = [1]
입력:
long long n = 1;

예상 출력:
std::vector<long long> expected = {1};
입력:
long n = 1;

예상 출력:
long[] expected = new long[] {1};

설명

The starting value is already 1, so no transformations are needed.

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

The sequence is generated by repeatedly applying one rule based on whether the current number is even or odd.

힌트 2

Keep appending each new value until you reach 1.

힌트 3

Watch out that the starting value itself and the final 1 must both appear in the result.

예상 복잡도

O(k) time, O(k) extra space, where k is the sequence length

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

# 코더 언어 시간 메모리 AI 평가 풀이
1 HJhettory Jurash Python 830 ms - 5/5 코드 보기

다른 사람의 풀이 보기

커뮤니티 솔루션

스포일러: 아래에 1개 전체 솔루션 있음 먼저 직접 풀어보세요. 다른 개발자의 코드와 AI 리뷰도 참고할 수 있습니다. 로그인하고 문제를 풀면 토론에 참여할 수 있습니다.