-
-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathHappyNumber.java
More file actions
38 lines (28 loc) · 682 Bytes
/
Copy pathHappyNumber.java
File metadata and controls
38 lines (28 loc) · 682 Bytes
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
package leetcode.easy;
import java.util.HashSet;
import java.util.Set;
/**
* Created by nikoo28 on 10/19/19 3:11 PM
*/
class HappyNumber {
boolean isHappy(int n) {
Set<Integer> usedIntegers = new HashSet<>();
while (true) {
// Find the sum of squares
int sum = 0;
while (n != 0) {
sum += Math.pow(n % 10, 2.0);
n = n / 10;
}
// If sum is 1, return true
if (sum == 1) return true;
// Else, the new number is the current sum
n = sum;
// Check if we have already encountered
// that number
if (usedIntegers.contains(n))
return false;
usedIntegers.add(n);
}
}
}