-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHappyNumberSolver.java
More file actions
36 lines (32 loc) · 856 Bytes
/
HappyNumberSolver.java
File metadata and controls
36 lines (32 loc) · 856 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
public class HappyNumberSolver {
public static void main(String[] args) {
int count = 0;
int sum = 0;
for (int i = 1; i <= 9999; i++) {
if (isHappy(i)) {
count++;
sum += i;
}
}
long result = (long) count * sum;
System.out.println(result);
}
// 행복 수 판별 함수
private static boolean isHappy(int n) {
java.util.Set<Integer> seen = new java.util.HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
n = sumOfSquares(n);
}
return n == 1;
}
private static int sumOfSquares(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
}