https://leetcode.com/problems/happy-number/

The key point for this question is to use a Set to keep recording
the number generated with each iteration. If we can’t add the new number
to the Set, the endless loop begins: return false. Another trick is to
get the last digit of a number, the

i = n % 10; // get the last digit
n = n / 10; // push one position right

would do that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while (set.add(n)) {
int total = 0;
while (n != 0) {
int i = n % 10;
n /= 10;
total += i * i;
}
n = total;
if (total == 1) {
return true;
}
}
return false;
}
}