Perfect Rank Private Jobs
Perfect RankPrivate Jobs
💼 Placement & IT Recruitment Prep
#3

Happy Number

Easy
Acceptance: 56.4%•Hash TableMathTwo Pointers•AmazonGoogleMicrosoftTCS DigitalInfosys DSEAppleUberCognizant

Problem Statement

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

A happy number is a number defined by the following process:

  • Starting with any positive integer, replace the number by the sum of the squares of its digits.
  • Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
  • Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

Examples

Example 1
Input: n = 19
Output: true
Explanation:

1² + 9² = 1 + 81 = 82 8² + 2² = 64 + 4 = 68 6² + 8² = 36 + 64 = 100 1² + 0² + 0² = 1 + 0 + 0 = 1 (Process ends in 1, so 19 is a happy number).

Example 2
Input: n = 2
Output: false
Explanation:

2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 (Enters an endless cycle containing 4, never reaches 1).

Example 3
Input: n = 7
Output: true
Explanation:

7 → 49 → 97 → 130 → 10 → 1 (Ends in 1).

Constraints

  • 1 <= n <= 2^31 - 1

Hints

1
2
3
4
5
6
7
8
9
10
Input n (positive integer):
Student & User Feedback

How was your experience on this page?

Your review & improvement suggestions help us refine tools, mock tests, and explanations — it takes only 10 seconds!

Feedback goes directly to our team at perfectrankofficial@gmail.com
Outstanding / Excellent! 🌟
Back to Top of Private Jobs Portal