- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHappyNumber.java
More file actions
Latest commit
42 lines (35 loc) · 1017 Bytes
/
Copy pathHappyNumber.java
File metadata and controls
42 lines (35 loc) · 1017 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
39
40
41
42
//Happy Number
importjava.util.Scanner;
classHappyNumber {
intn = 0;
publicintsplitDigits(intx) {
n = 0; // Resetting n to 0 before splitting the digits
while (x > 0) {
inta = x % 10;
x = x / 10;
n += a * a;
}
returnn;
}
publicbooleanisHappy() {
intslow = n;
intfast = n;
do {
slow = splitDigits(slow);
fast = splitDigits(splitDigits(fast));
} while (slow != fast);
returnslow == 1;
}
publicstaticvoidmain(String[] args) {
Scannerinput = newScanner(System.in);
intx = input.nextInt();
HappyNumberobj = newHappyNumber();
obj.splitDigits(x);
booleanisHappy = obj.isHappy();
if (isHappy) {
System.out.println(x + " is a happy number");
} else {
System.out.println(x + " is not a happy number");
}
}
}