LeetCode: Happy Number

LeetCode: Happy Number

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
27
28
29
30
31
32

/**
* Created by hzhou on 4/22/15. [email protected]
*/
public class HappyNumber {
public boolean isHappy(int n) {
if (n < 1) {
return false;
}
Set<Integer> set = new HashSet<Integer>();
int result = n;
while (true) {
result = calc(result);
if (result == 1) {
return true;
}
if (set.contains(result)) {
return false;
}
set.add(result);
}
}
private int calc(int n) {
int result = 0;
while (n > 0) {
int x = n % 10;
n /= 10;
result += x * x;
}
return result;
}
}