Happy Number
Problem Statement
You’re a number mystic checking if a number is "happy"—repeatedly sum the squares of its digits until it reaches 1 (happy) or loops (unhappy). This easy-level set challenge is a cyclic quest—use hashing to spot the loop!
Example
Input: n = 19
Output: true (1²+9²=82, 8²+2²=68, ..., 1)
Input: n = 2
Output: false (Loops: 4, 16, 37, ...)
Input: n = 7
Output: true (Reaches 1)
Code
Java
Python
JavaScript
public class Solution {
public boolean isHappy(int n) {
Set seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
n = getSumOfSquares(n);
}
return n == 1;
}
private int getSumOfSquares(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
}
def is_happy(n):
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
function isHappy(n) {
let seen = new Set();
while (n !== 1 && !seen.has(n)) {
seen.add(n);
n = String(n).split('').reduce((sum, d) => sum + d * d, 0);
}
return n === 1;
}
Explanation
- Set Insight: Detect cycles with a set of seen numbers.
- Flow: Compute sum of squares, check if 1 or looped, repeat.
- Example Walkthrough: 19 → 82 → 68 → 65 → 61 → 37 → 58 → 89 → 145 → 42 → 20 → 4 → 16 → 37 (loop) → false.
- Math Fact: Unhappy numbers enter a cycle (e.g., 4→16→37).
- Alternative: Floyd’s cycle detection works too.
Note
Time complexity: O(log n), Space complexity: O(log n). A mystical journey to happiness with sets!
