Skip to content

Latest commit

 

History

History
84 lines (49 loc) · 1.4 KB

File metadata and controls

84 lines (49 loc) · 1.4 KB

LeetCode – 202. Happy Number

Problem Statement

A number is called happy if repeatedly replacing it with the sum of the squares of its digits eventually results in 1.
If it enters a cycle that does not include 1, it is not happy.

Your task is to determine whether a number is happy.

Description

Given a number n:

  1. Split it into digits

  2. Square each digit

  3. Take the sum

  4. Repeat this process

If the process reaches 1 → happy number
If it cycles → unhappy number

Input

A single integer n

Output

Boolean: true if happy, false otherwise

Examples

Example 1
Input:
n = 19

Process:
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1

Output:
true

Explanation:
The sequence reaches 1.

Example 2
Input:
n = 2

Process enters a loop (never becomes 1)

Output:
false

Constraints

  • 1 ≤ n ≤ 2³¹ - 1

Hints

  • Use a set to detect repeated values (cycle detection).

  • Or use Floyd’s cycle algorithm (slow/fast pointer).

  • The sum of squares operation always reduces the magnitude.

Explanation

If a number is happy, the chain of "sum of squares of digits" will eventually shrink to 1.
If it ever repeats a value, a cycle has formed → not a happy number.

Using a set:

  • Keep computing sums

  • If a sum repeats → cycle → false

  • If sum becomes 1 → true