Reference: LeetCode
Difficulty: Easy

Problem

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
2
3
4
5
6
7
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Follow up: Use $O(1)$ space.

Analysis

Hash Set

Since you will get repeat numbers again and again, we can put all visited numbers in a hash set to know whether we can stop trying.

I list two ways of writing squareSum().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
n = squareSum(n);
}
return n == 1;
}
// 1
private int squareSum(int n) {
int sum = 0;
do {
int d = n % 10;
sum += d * d;
n /= 10;
} while (n != 0);
}
// 2
private int squareSum(int n) {
String s = "" + n;
for (char ch : s.toCharArray()) {
int digit = ch - '0';
sum += digit * digit;
}
return sum;
}

Time: N/A
Space: N/A It depends on the input.

Cycle Detection

We can solve it without extra space.

1
2
3
4
5
6
7
8
9
public boolean isHappy(int n) {
int slow = n;
int fast = n;
do {
slow = squareSum(slow);
fast = squareSum(squareSum(fast));
} while (slow != fast); // stops at slow == fast
return slow == 1;
}

Time: N/A
Space: $O(1)$


Comment