forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsHappy.java
More file actions
51 lines (45 loc) · 1.12 KB
/
IsHappy.java
File metadata and controls
51 lines (45 loc) · 1.12 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
package normal;
import java.util.HashSet;
/**
* @program JavaBooks
* @description: 202.快乐数
* @author: mf
* @create: 2019/11/06 10:15
*/
public class IsHappy {
public static void main(String[] args) {
System.out.println(isHappy(19));
System.out.println(isHappy2(19));
}
/**
* 递归,但有4的话,就一直循环,所以是4就false
* @param n
* @return
*/
private static boolean isHappy(int n) {
if (n == 1) return true;
if (n != 4) {
int sum = 0, k = n;
while (k > 0) {
sum += (k % 10) * (k % 10);
k /= 10;
}
return isHappy(sum);
}
return false;
}
private static boolean isHappy2(int n) {
if (n == 1) return true;
HashSet<Integer> set = new HashSet<>();
while (2 > 1) {
int sum = 0;
while (n > 0) {
sum += (n % 10) * (n % 10);
n /= 10;
}
if (sum == 1) return true;
if (!set.add(sum)) return false;
n = sum;
}
}
}