Back to Problem
Official 419 views

Editorial: Happy Number

by admin ·

4

1 Intuition

Either we reach 1, or we revisit a number and are stuck in a cycle.

2 Approach

Iterate the digit-square map and remember seen values (or use Floyd's cycle detection).

3 Complexity Analysis

Each step shrinks large numbers quickly, so the work is effectively O(log n) per step with a small bounded number of steps.

4 Solution Code

class Solution:
    def isHappy(self, n: int) -> bool:
        seen = set()
        while n != 1 and n not in seen:
            seen.add(n)
            n = sum(int(d) ** 2 for d in str(n))
        return n == 1

5 Code Walkthrough

The reference solution below implements the approach step by step.