-
Notifications
You must be signed in to change notification settings - Fork 0
/
HappyNumber.java
47 lines (39 loc) · 967 Bytes
/
HappyNumber.java
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
import java.util.*;
class HappyNumber {
public static void main(String[] args) {
isHappy(19);
}
public static boolean isHappy(int n) {
if(n < 10) {
if(n==1||n==7)
return true;
else
return false;
}
int b;
int sum=0;
while(n > 0) {
b = n % 10;
sum = sum + b*b;
n = n / 10;
}
return isHappy(sum);
}
/* ANNOTHER SOLUTION */
public boolean isHappy2(int n) {
Set<Integer> set = new HashSet<>();
while(getSquareSum(n) != 1){
n = getSquareSum(n);
if(!set.add(n))return false;
}
return true;
}
private int getSquareSum(int n){
int result = 0;
while(n != 0){
result += Math.pow(n%10,2);
n = n/10;
}
return result;
}
}