Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Collatz Sequence

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

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

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

Ví dụ

Ví dụ 1
Đầu vào:
n = 6

Kết quả mong đợi:
expected = [6, 3, 10, 5, 16, 8, 4, 2, 1]
Đầu vào:
long long n = 6;

Kết quả mong đợi:
std::vector<long long> expected = {6, 3, 10, 5, 16, 8, 4, 2, 1};
Đầu vào:
long n = 6;

Kết quả mong đợi:
long[] expected = new long[] {6, 3, 10, 5, 16, 8, 4, 2, 1};

Giải thích

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

Ví dụ 2
Đầu vào:
n = 1

Kết quả mong đợi:
expected = [1]
Đầu vào:
long long n = 1;

Kết quả mong đợi:
std::vector<long long> expected = {1};
Đầu vào:
long n = 1;

Kết quả mong đợi:
long[] expected = new long[] {1};

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

Keep appending each new value until you reach 1.

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.