CodeSpeek

Happy Number

Easy · Math & Geometry

You are given a positive integer. Repeatedly replace the number with the sum of the squares of its decimal digits. Return true if this process eventually reaches the value 1, and return false if it instead loops forever in a cycle that never includes 1.

Examples

Input:  n = 19
Output: true
Why:    1^2+9^2=82, 8^2+2^2=68, 6^2+8^2=100, 1^2+0^2+0^2=1, so it reaches 1.
Input:  n = 2
Output: false
Why:    Repeatedly squaring and summing digits of 2 falls into a cycle that never reaches 1.
Input:  n = 7
Output: true
Why:    The sequence 7, 49, 97, 130, 10, 1 ends at 1.

Constraints

1 <= n <= 2^31 - 1

Practise it by voice

Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.

Practise Happy Number

This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Happy Number. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.