Problem Set
#3
Happy Number
EasyAcceptance: 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 include1. - 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 = 19Output:
trueExplanation:
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 = 2Output:
falseExplanation:
2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 (Enters an endless cycle containing 4, never reaches 1).
Example 3
Input:
n = 7Output:
trueExplanation:
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):