-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHappyNumber.java
More file actions
51 lines (40 loc) · 1.21 KB
/
HappyNumber.java
File metadata and controls
51 lines (40 loc) · 1.21 KB
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
43
44
45
46
47
48
49
50
51
import java.util.HashMap;
import java.util.Map;
class HappyNumber {
//TO avoid case of "P - problem situation like in linked list"
//eg number 22
Map<Integer,Boolean> checkMap = new HashMap<Integer,Boolean> ();
private int squareAndAdd(int num)
{
int sum = 0;
while(num > 0) {
int rem = num % 10;
num = num /10;
sum += (rem * rem);
}
return sum;
}
private boolean verifyHappy(String input) {
int num = Integer.parseInt(input);
while(num > 1 && !checkMap.containsKey(num)) {
//fill map when we add num
checkMap.put(num, true);
num = squareAndAdd(num);
}
if (num == 1) {
return true;
}
return false;
}
public static void main(String args[]) {
// String input = args[0];
String input = "44";
HappyNumber hp = new HappyNumber();
boolean isHappy = hp.verifyHappy(input);
if(true == isHappy) {
System.out.println("Number is Happy");
}else {
System.out.println("Number is not Happy");
}
}
}