ExamAdda Logo

Happy Number

Easy

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

A happy number is defined by the following process:

1. Replace the number by the sum of the squares of its digits.
2. Repeat the process until the number becomes 1.
3. If the process ends at 1, the number is happy.
4. If the process enters a cycle that never reaches 1, the number is not happy.

Return true if n is a happy number; otherwise, return false.

Example 1

Input

19

Output

true

Explanation

1² + 9² = 82

8² + 2² = 68

6² + 8² = 100

1² + 0² + 0² = 1

Since the process reaches 1, 19 is a happy number.

Example 2

Input

2

Output

false

Explanation

Repeating the process eventually enters a cycle that never reaches 1.

Therefore, 2 is not a happy number.

Constraints

1 ≤ n ≤ 2³¹ - 1

Hints:

Hint 1

Create a helper function that returns the sum of the squares of the digits of a number.

Hint 2

If a number repeats, the process has entered a cycle. Use a HashSet (or Floyd's Cycle Detection) to detect repeated values.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Jul 29, 2026

Last updated

Jul 29, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output