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
🏆 All Time Leaderboard
Contest runs January 1, 1970 - December 31, 9999. Complete challenges to climb the leaderboard!
Points are calculated for challenges completed during the contest period.