Write an algorithm to determine if a number n
is happy.
A happy number is a number defined by the following process:
Return true
if n
is a happy number, and false
if not.
Example 1:
Input: n = 19
Output: true
Explanation:
1<sup>2</sup> + 9<sup>2</sup> = 82
8<sup>2</sup> + 2<sup>2</sup> = 68
6<sup>2</sup> + 8<sup>2</sup> = 100
1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1
Example 2:
Input: n = 2
Output: false
Constraints:
1 <= n <= 2<sup>31</sup> - 1
Determine if a number n
is a happy number. A happy number is defined by repeatedly replacing the number by the sum of the squares of its digits until it equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Return true
if n
is a happy number, and false
if not.
A brute force solution involves simulating the process as described, but we need a way to detect cycles to avoid infinite loops. We can use a HashSet
to keep track of the numbers we've seen so far. If we encounter a number that's already in the set, we know we're in a cycle and the number is not happy.
HashSet
to store the numbers seen.n
is not 1 and is not in the HashSet
:
n
to the HashSet
.n
and update n
with the result.n
is 1, return true
. Otherwise, return false
.import java.util.HashSet;
import java.util.Set;
public class HappyNumber {
public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
int sum = 0;
int num = n;
while (num > 0) {
int digit = num % 10;
sum += digit * digit;
num /= 10;
}
n = sum;
}
return n == 1;
}
}
HashSet
. In the worst case it is O(1).An optimized solution uses Floyd's Cycle Detection Algorithm, also known as the "tortoise and hare" algorithm. We use two pointers, one moving one step at a time (tortoise) and another moving two steps at a time (hare). If n
is a happy number, the hare will eventually reach 1. If n
is not a happy number, the two pointers will eventually meet at a number other than 1.
slow
and fast
, to n
.fast
is not 1 and slow
is not equal to fast
:
slow
one step: slow = sumOfSquares(slow)
fast
two steps: fast = sumOfSquares(sumOfSquares(fast))
fast
is 1, return true
. Otherwise, return false
.public class HappyNumber {
private int sumOfSquares(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
public boolean isHappy(int n) {
int slow = n;
int fast = n;
do {
slow = sumOfSquares(slow);
fast = sumOfSquares(sumOfSquares(fast));
} while (slow != fast);
return slow == 1;
}
}
slow
and fast
, regardless of the input size.true
immediately.HashSet
approach and the Floyd's cycle detection approach.