Math Number tricks
89. Happy Number
You are given a positive integer n. One step replaces the number with the sum of the squares of its
digits. For example, one step turns 203 into 2² + 0² + 3² = 13.
Start from n and take steps, again and again. n is happy if the numbers reach 1 at some point. Return
true if n is happy and false if it is not.
1 itself is happy, since it is already 1. In C++, Java, Go, Rust and C#, n is a 64-bit integer.
Example 1
Input: n = 7
trueExplanation: The steps go 7 → 49 → 97 → 130 → 10 → 1.
Example 2
Input: n = 2
falseExplanation: The steps go 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. The numbers are back at 4, so from here they repeat the same eight numbers forever and never reach 1.
Example 3
Input: n = 1000000000000000
trueExplanation: The digits are a 1 and fifteen 0s, so one step gives 1² = 1.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1015
Clarifying questions
What you would ask an interviewer before writing any code.