Skip to content

Commit 1fc46aa

Browse files
committed
快乐数字
1 parent 1ad3907 commit 1fc46aa

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.crossoverjie.algorithm;
2+
3+
import java.util.HashSet;
4+
import java.util.Set;
5+
6+
/**
7+
* Function: 判断一个数字是否为快乐数字 19 就是快乐数字 11就不是快乐数字
8+
*
9+
* @author crossoverJie
10+
* Date: 04/01/2018 14:12
11+
* @since JDK 1.8
12+
*/
13+
public class HappyNum {
14+
15+
public boolean isHappy(int number) {
16+
Set<Integer> set = new HashSet<>(30);
17+
while (number != 1) {
18+
int sum = 0;
19+
while (number > 0) {
20+
//计算当前值的每位数的平方 相加的和 在放入set中,如果存在相同的就认为不是 happy数字
21+
sum += (number % 10) * (number % 10);
22+
number = number / 10;
23+
}
24+
if (set.contains(sum)) {
25+
return false;
26+
} else {
27+
set.add(sum);
28+
}
29+
number = sum;
30+
}
31+
return true;
32+
}
33+
34+
35+
public static void main(String[] args) {
36+
int num = 345;
37+
int i = num % 10;
38+
int i1 = num / 10;
39+
int i2 = i1 / 10;
40+
System.out.println(i);
41+
System.out.println(i1);
42+
System.out.println(i2);
43+
}
44+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.crossoverjie.algorithm;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
public class HappyNumTest {
7+
@Test
8+
public void isHappy() throws Exception {
9+
HappyNum happyNum = new HappyNum() ;
10+
boolean happy = happyNum.isHappy(19);
11+
Assert.assertEquals(happy,true);
12+
}
13+
14+
@Test
15+
public void isHappy2() throws Exception {
16+
HappyNum happyNum = new HappyNum() ;
17+
boolean happy = happyNum.isHappy(11);
18+
Assert.assertEquals(happy,false);
19+
}
20+
21+
@Test
22+
public void isHappy3() throws Exception {
23+
HappyNum happyNum = new HappyNum() ;
24+
boolean happy = happyNum.isHappy(100);
25+
System.out.println(happy);
26+
}
27+
28+
}

0 commit comments

Comments
 (0)