【LeetCode】202 - Happy Number
2024-08-27 11:17:47
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: 19 is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
Solution: 辅助函数;循环计算每位数字的平方和,直到出现结果为1(返回true)或者重复(返回false)
class Solution {
public:
bool isHappy(int n) {
map<int,bool> m;
int ret=sum(n);
while(ret!=){
if(m[ret]==true)return false;
m[ret]=true;
ret=sum(ret);
}
return true;
}
int sum(int n){
int ret=;
while(n){
ret += (n%)*(n%); //不支持(n%10)^2
n /= ;
}
return ret;
}
};
最新文章
- JavaScript面向对象之我见
- c#.net 生成清晰缩略图
- 使用MS Test进行单元测试
- Android应用开发中半透明效果实现方案
- linux开机启动mongodb
- 关于在Servelet中如何获取当前时间的操作
- .NET Core 和 ASP.NET 5 RC1 发布
- Java中接口作为方法的返回
- LeetCode(169)Majority Element and Majority Element II
- IPoilygon转IPoint
- linux驱动开发之GCC问题
- 3DMax的OFusion插件使用问题
- C语言内存对齐(2)
- [Python]基于K-Nearest Neighbors[K-NN]算法的鸢尾花分类问题解决方案
- 【Linux】解决";no member named &#39;max_align_t&#39;
- Hue添加MySQL数据库
- c++ try catch 问题
- 8.17 一个博客demo
- oracle中如何判断blob类型字段是否为空
- MapReduce求最大值最小值问题
热门文章
- c# 计算1-100之间的所有质数(素数)的和
- asp.net MVC3 “System.Web.Mvc.ModelClientValidationRule”问题
- ASP.NET 4.0 Webform Bundles 压缩css, js,为什么放到服务器不行
- UVa 644 Immediate Decodability
- HDU 1240 (简单三维广搜) Asteroids!
- LA 3905 Meteor
- 另类方法解决设计Web页面出现:Error Creating Control
- HDU 5326 work (回溯,树)
- Linux技巧:一次删除一百万个文件最快方法
- Mac 上安装MySQL