Paths Subjects Questions Quizzes Pricing Search
Intermediate Open Pro

Happy Number

Write an algorithm to determine if a number n is a happy number.

A happy number is defined by the following process:

  1. Starting with any positive integer, replace the number by the sum of the squares of its digits.
  2. Repeat the process until the number equals 1 (in which case it is happy), or it enters a cycle that does not include 1 (in which case it is not happy, and the process loops forever).

Return True if n is happy, and False otherwise.

Example 1

Input: n = 19

Output: True

Explanation: 1^2 + 9^2 = 82, 8^2 + 2^2 = 68, 6^2 + 8^2 = 100, 1^2 + 0^2 + 0^2 = 1. The sequence reaches 1, so 19 is happy.

Example 2

Input: n = 2

Output: False

Explanation: repeatedly summing squared digits from 2 enters a cycle (4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> ...) that never reaches 1.

Constraints

  • 1 <= n <= 2^31 - 1
  • Aim for O(1) extra space beyond a small constant number of variables (i.e., avoid storing every value you have seen).

Share this question

← Back to Fast and Slow Pointers practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.