力扣:202. 快乐数

This commit is contained in:
huangge1199 2021-02-04 16:52:25 +08:00
parent 58116c5ec6
commit b1b6574de4
7 changed files with 85 additions and 12 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
/.idea/
/**/*.iml
/**/src/test/

View File

@ -0,0 +1,39 @@
package com.code.leet.Official.t20210204;
import java.util.HashSet;
import java.util.Set;
/**
* 编写一个算法来判断一个数 n 是不是快乐数
*
* 快乐数定义为
*
* 对于一个正整数每一次将该数替换为它每个位置上的数字的平方和
* 然后重复这个过程直到这个数变为 1也可能是 无限循环 但始终变不到 1
* 如果 可以变为  1那么这个数就是快乐数
* 如果 n 是快乐数就返回 true 不是则返回 false
*
* 来源力扣LeetCode
* 链接https://leetcode-cn.com/problems/happy-number
* 著作权归领扣网络所有商业转载请联系官方授权非商业转载请注明出处
*/
public class IsHappy {
private int getNext(int n) {
int totalSum = 0;
while (n > 0) {
int d = n % 10;
n = n / 10;
totalSum += d * d;
}
return totalSum;
}
public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
n = getNext(n);
}
return n == 1;
}
}

View File

@ -1,6 +1,6 @@
package com.code.leet.study.t20200212;
import entiy.ListNode;
import com.code.leet.entiy.ListNode;
/**
* 2. 两数相加

View File

@ -1,6 +1,7 @@
package com.code.leet.study.t20200213;
import entiy.TreeNode;
import com.code.leet.entiy.TreeNode;
/**
* @Author: hyy

View File

@ -5,7 +5,7 @@ package com.code.leet.study.t20200213;
* @Date: 2020-02-13 19:17
*/
import entiy.NestedInteger;
import com.code.leet.entiy.NestedInteger;
import java.util.ArrayList;
import java.util.Iterator;

View File

@ -1,10 +1,11 @@
package com.code.leet.study.t20210204;
/**
*
*/
import java.util.ArrayList;
import java.util.List;
public class IsHappy {
public boolean isHappy(int n) {
private boolean is(int n, List<Integer> nums) {
boolean is = false;
int sum = 0;
do {
@ -13,13 +14,18 @@ public class IsHappy {
n = n / 10;
} while (n >= 10);
sum += n * n;
if (sum >= 10) {
isHappy(sum);
} else {
is = sum == 1;
if (sum == 1) {
is = true;
} else if (!nums.contains(sum)) {
nums.add(sum);
is = is(sum, nums);
}
return is;
}
public boolean isHappy(int n) {
List<Integer> nums = new ArrayList<>();
return is(n, nums);
}
}

26
pom.xml
View File

@ -14,6 +14,32 @@
<module>LintCode</module>
<module>LuoGu</module>
</modules>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.14.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.shrinkwrap</groupId>
<artifactId>shrinkwrap-api</artifactId>
<version>1.2.6</version>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<version>1.4.1.Final</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>