202:快乐数

This commit is contained in:
huangge1199 2021-06-07 10:39:47 +08:00
parent b09e904694
commit fbea1d27af
2 changed files with 121 additions and 0 deletions

View File

@ -0,0 +1,80 @@
//编写一个算法来判断一个数 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)
}

View File

@ -0,0 +1,41 @@
<p>编写一个算法来判断一个数 <code>n</code> 是不是快乐数。</p>
<p>「快乐数」定义为:</p>
<ul>
<li>对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。</li>
<li>然后重复这个过程直到这个数变为 1也可能是 <strong>无限循环</strong> 但始终变不到 1。</li>
<li>如果 <strong>可以变为</strong>  1那么这个数就是快乐数。</li>
</ul>
<p>如果 <code>n</code> 是快乐数就返回 <code>true</code> ;不是,则返回 <code>false</code></p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>19
<strong>输出:</strong>true
<strong>解释:
</strong>1<sup>2</sup> + 9<sup>2</sup> = 82
8<sup>2</sup> + 2<sup>2</sup> = 68
6<sup>2</sup> + 8<sup>2</sup> = 100
1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>n = 2
<strong>输出:</strong>false
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= n <= 2<sup>31</sup> - 1</code></li>
</ul>
<div><div>Related Topics</div><div><li>哈希表</li><li>数学</li></div></div>\n<div><li>👍 615</li><li>👎 0</li></div>