leet-code/src/main/java/leetcode/editor/cn/HappyNumber.java
2021-06-07 10:39:47 +08:00

80 lines
1.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//编写一个算法来判断一个数 n 是不是快乐数。
//
// 「快乐数」定义为:
//
//
// 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
// 然后重复这个过程直到这个数变为 1也可能是 无限循环 但始终变不到 1。
// 如果 可以变为 1那么这个数就是快乐数。
//
//
// 如果 n 是快乐数就返回 true ;不是,则返回 false 。
//
//
//
// 示例 1
//
//
//输入19
//输出true
//解释:
//12 + 92 = 82
//82 + 22 = 68
//62 + 82 = 100
//12 + 02 + 02 = 1
//
//
// 示例 2
//
//
//输入n = 2
//输出false
//
//
//
//
// 提示:
//
//
// 1 <= n <= 231 - 1
//
// Related Topics 哈希表 数学
// 👍 615 👎 0
package leetcode.editor.cn;
import java.util.HashSet;
import java.util.Set;
//202:快乐数
public class HappyNumber {
public static void main(String[] args) {
//测试代码
Solution solution = new HappyNumber().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
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;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}