Happy Number easy
Problem Statement
Write an algorithm to determine if a number 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, and 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 numbers.
Example 1:
Input: n = 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
Example 2:
Input: n = 2 Output: false
Steps
- Initialization: Create a
HashSet
to store the numbers encountered during the process. This set will help detect cycles. - Iteration: While the number
n
is not 1 and has not been encountered before (not in theHashSet
):- Calculate the sum of the squares of its digits.
- Add the current number
n
to theHashSet
. - Update
n
with the calculated sum.
- Result: If
n
becomes 1, returntrue
(happy number). Otherwise, returnfalse
(unhappy number, it entered a cycle).
Explanation
The algorithm uses a HashSet
to efficiently detect cycles. If a number repeats during the process, it means the number will loop endlessly without reaching 1, hence it's not a happy number. The HashSet
provides constant-time (O(1)
) lookups, making the cycle detection very fast. The algorithm terminates when either 1 is reached or a cycle is detected.
Code
import java.util.HashSet;
import java.util.Set;
class Solution {
public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>(); // HashSet to detect cycles
while (n != 1 && !seen.contains(n)) {
seen.add(n);
n = sumOfSquaresOfDigits(n);
}
return n == 1;
}
private int sumOfSquaresOfDigits(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
}
Complexity
- Time Complexity: O(log n). The number of iterations is roughly logarithmic because the number of digits decreases as the number gets smaller. Each iteration involves a constant number of operations to calculate the sum of squares. However, in worst case scenarios, it might take longer to hit a cycle.
- Space Complexity: O(log n). The
HashSet
can store at most O(log n) distinct numbers, where n is the input number. The space used is proportional to the number of digits in the input number.