Happy Number Explained
Problem Statement
A happy number is a number that, when you repeatedly replace it with the sum of the squares of its digits, eventually reaches 1. If it loops endlessly in a cycle that does not include 1, it is not happy. Given an integer n
, determine if it is a happy number. This problem tests cycle detection in iterative processes.
Example
Input: n = 19
Output: true
Explanation: 1^2 + 9^2 = 82, 8^2 + 2^2 = 68, 6^2 + 8^2 = 100, 1^2 + 0^2 + 0^2 = 1.
Code
Java
Python
JavaScript
public class Solution { public boolean isHappy(int n) { Setseen = new HashSet<>(); while (n != 1 && !seen.contains(n)) { seen.add(n); int sum = 0; while (n > 0) { int digit = n % 10; sum += digit * digit; n /= 10; } n = sum; } return n == 1; } public static void main(String[] args) { Solution sol = new Solution(); System.out.println(sol.isHappy(19)); // true } }
def is_happy(n): seen = set() while n != 1 and n not in seen: seen.add(n) sum_squares = 0 while n > 0: digit = n % 10 sum_squares += digit * digit n //= 10 n = sum_squares return n == 1 # Example usage print(is_happy(19)) # True
function isHappy(n) { const seen = new Set(); while (n !== 1 && !seen.has(n)) { seen.add(n); let sum = 0; while (n > 0) { let digit = n % 10; sum += digit * digit; n = Math.floor(n / 10); } n = sum; } return n === 1; } // Example usage console.log(isHappy(19)); // true
Explanation
- Use a set to track numbers seen during the process.
- For each number, compute the sum of the squares of its digits.
- Update
n
to this sum and repeat. - If
n
becomes 1, it’s a happy number. - If
n
repeats (cycle detected), it’s not happy.
Note
The time complexity is O(log n) for most inputs, but worst-case analysis is complex due to number theory. Floyd’s cycle detection can be used instead of a set to optimize space to O(1).