The Collatz conjecture defines a process for any positive integer. Given an integer n, perform the following operations repeatedly until n becomes 1:
- If
nis even, replacenwithn / 2. - If
nis odd, replacenwith3 * n + 1.
It is conjectured that this process will always reach 1, no matter the starting value of n. Your task is to determine how many steps it takes for a given n to reach 1.
Constraints:
≤n≤
Example 1:
Input: n = 6 Output: 8 Explanation: The sequence for n = 6 proceeds as follows:
- Step 1: 6 is even, so the next number is 6 / 2 = 3.
- Step 2: 3 is odd, so the next number is 3 * 3 + 1 = 10.
- Step 3: 10 is even, so the next number is 10 / 2 = 5.
- Step 4: 5 is odd, so the next number is 3 * 5 + 1 = 16.
- Step 5: 16 is even, so the next number is 16 / 2 = 8.
- Step 6: 8 is even, so the next number is 8 / 2 = 4.
- Step 7: 4 is even, so the next number is 4 / 2 = 2.
- Step 8: 2 is even, so the next number is 2 / 2 = 1.
Example 2:
Input: n = 1 Output: 0
Example 3:
Input: n = 3 Output: 7
Accepted
3.2k/5.8k
Acceptance Rate55.7%
Ask AI Assistant

Ask AI Assistant
Ask me anything about this coding question!
Test Cases
Input
n =
Output
Expected