-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHappyNumber.java
More file actions
53 lines (48 loc) · 1.21 KB
/
Copy pathHappyNumber.java
File metadata and controls
53 lines (48 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
52
53
package com.wgcris.LeetcodeAlgorithm;
import java.util.HashSet;
import java.util.Set;
/*
* happyNumber eg:1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
*/
public class HappyNumber {
public static boolean isHappy(int n){
if (n <= 0) return false;
HashSet<Integer> set = new HashSet<Integer>();
int m=0;
while(n !=1 && !set.contains(n)) {
set.add(n);
m = n;
n = 0;
while(m != 0) {
n += (m%10)*(m%10);
m = m/10;
}
}
if (n == 1) return true;
else return false;
}
public static boolean isHappy1(int n){
if(n<=0)return false;
Set<Integer> set =new HashSet<Integer>();
set.add(n);
while(n!=1){
int result=0;
while(n!=0){
result+=(n%10)*(n%10);
n/=10;
}
if(!set.add(result)) return false;
else {
set.add(result);
n=result;
}
}
return true;
}
public static void main(String[] args){
System.out.println(isHappy1(100));
}
}