题目英文
Write an algorithm to determine if a number is “happy”.
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example:
Input: 19
Output: true
Explanation:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
题目中文
编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19
输出: true
解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1输入:7
输出:true输入: 20
输出: false
解释:
20 => 4 + 0
4 => 16
16 => 1 + 36
37 => 9 + 49
58 => 25 + 64
89 => 64 + 81
145 => 1 + 16 + 25
42 => 16 + 4
20 可以看到, 20再次重复出现了, 所以永远不可能等于1
算法实现
// 首先定义一个Set集合,用来存放计算后的平方和m,
// 如果m在Set中已存在,即进入了死循环,则退出;
// 如果m不存在Set,则将m放入Set;
// 直至找到平方和为1或者进入死循环就退出。public class Solution {public bool IsHappy(int n) {HashSet<int> set = new HashSet<int>();int m = 0;while (true){while (n != 0){m += (int)Math.Pow(n % 10,2);n /= 10;}if (m == 1){return true;}if (set.Contains(m))return false;set.Add(m);n = m;m = 0;} }
}
实验结果
相关图文:
- LeetCode实战:删除链表的倒数第N个节点
- LeetCode实战:合并两个有序链表
- LeetCode实战:两两交换链表中的节点
- LeetCode实战:旋转链表
- LeetCode实战:相同的树
- LeetCode实战:对称二叉树
- LeetCode实战:二叉树的最大深度
- LeetCode实战:搜索二维矩阵
- LeetCode实战:将有序数组转换为二叉搜索树
- 资料分享:数学建模资料分享 – 图论部分
- 资料分享:数学建模资料分享 – 神经网络部分
- 如何利用 C# 实现 K 最邻近算法?
- 如何利用 C# 实现 K-D Tree 结构?
- 如何利用 C# + KDTree 实现 K 最邻近算法?
- 如何利用 C# 对神经网络模型进行抽象?
- 如何利用 C# 实现神经网络的感知器模型?
- 如何利用 C# 实现 Delta 学习规则?
- 如何利用 C# 实现 误差反向传播 学习规则?
- 如何利用 C# 爬取带 Token 验证的网站数据?
- 如何利用 C# 向 Access 数据库插入大量数据?
- 如何利用 C# + Python 破解猫眼电影的反爬虫机制?