Given a positive integer n, return the length of the Collatz sequence starting from n. The Collatz sequence is generated by repeatedly applying the rule: if the current value is even, divide it by 2; if odd, multiply by 3 and add 1. The sequence terminates when the value reaches 1. The length includes both the starting value and the terminal 1. Return null when the input is null, zero, or negative. Use Long arithmetic internally because intermediate values may exceed the Integer range.
Examples:
Input: n = 1
Output: 1
Explanation: The sequence is just [1].
Input: n = 6
Output: 9
Explanation: 6, 3, 10, 5, 16, 8, 4, 2, 1 contains 9 values.
Input: n = 7
Output: 17
Explanation: 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1.
Input: n = 0
Output: null
Explanation: Zero is not a valid starting value.
Input: n = null
Output: null
Explanation: Null input returns null.
Apex Code Editor
Welcome to Lightning Challenge!
How It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Contest Alert
🏆 #CodeEveryDay August 2026
Contest runs August 1 - 31. Complete challenges to climb the leaderboard!
Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.