-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathHappyNumber.java
40 lines (38 loc) · 973 Bytes
/
HappyNumber.java
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
33
34
35
36
37
38
39
40
package io.ziheng.hashtable.leetcode;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* LeetCode 202. Happy Number
* https://leetcode.com/problems/happy-number/
*/
public class HappyNumber {
public boolean isHappy(int n) {
int val = n;
Set<Integer> aSet = new HashSet<>();
while (val != 1) {
if (aSet.contains(val)) {
return false;
} else {
aSet.add(val);
}
int nextVal = 0;
List<Integer> digits = findDigits(val);
for (int digit : digits) {
nextVal += digit * digit;
}
val = nextVal;
}
return true;
}
private List<Integer> findDigits(int n) {
List<Integer> list = new LinkedList<>();
while (n > 0) {
list.add(n % 10);
n /= 10;
}
return list;
}
}
/* EOF */