-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHappyNumberCheck.java
More file actions
34 lines (30 loc) · 939 Bytes
/
HappyNumberCheck.java
File metadata and controls
34 lines (30 loc) · 939 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
// 33. Write a program to check if a given number is a happy number.
import java.util.HashSet;
public class HappyNumberCheck {
public static void main(String[] args) {
int num = 19;
boolean isHappy = isHappyNumber(num);
if (isHappy) {
System.out.println(num + " is a happy number.");
} else {
System.out.println(num + " is not a happy number.");
}
}
public static boolean isHappyNumber(int num) {
HashSet<Integer> seen = new HashSet<>();
while (num != 1 && !seen.contains(num)) {
seen.add(num);
num = getNextNumber(num);
}
return num == 1;
}
public static int getNextNumber(int num) {
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += digit * digit;
num /= 10;
}
return sum;
}
}