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;
}
};

最新文章

  1. JavaScript面向对象之我见
  2. c#.net 生成清晰缩略图
  3. 使用MS Test进行单元测试
  4. Android应用开发中半透明效果实现方案
  5. linux开机启动mongodb
  6. 关于在Servelet中如何获取当前时间的操作
  7. .NET Core 和 ASP.NET 5 RC1 发布
  8. Java中接口作为方法的返回
  9. LeetCode(169)Majority Element and Majority Element II
  10. IPoilygon转IPoint
  11. linux驱动开发之GCC问题
  12. 3DMax的OFusion插件使用问题
  13. C语言内存对齐(2)
  14. [Python]基于K-Nearest Neighbors[K-NN]算法的鸢尾花分类问题解决方案
  15. 【Linux】解决&quot;no member named &#39;max_align_t&#39;
  16. Hue添加MySQL数据库
  17. c++ try catch 问题
  18. 8.17 一个博客demo
  19. oracle中如何判断blob类型字段是否为空
  20. MapReduce求最大值最小值问题

热门文章

  1. c# 计算1-100之间的所有质数(素数)的和
  2. asp.net MVC3 “System.Web.Mvc.ModelClientValidationRule”问题
  3. ASP.NET 4.0 Webform Bundles 压缩css, js,为什么放到服务器不行
  4. UVa 644 Immediate Decodability
  5. HDU 1240 (简单三维广搜) Asteroids!
  6. LA 3905 Meteor
  7. 另类方法解决设计Web页面出现:Error Creating Control
  8. HDU 5326 work (回溯,树)
  9. Linux技巧:一次删除一百万个文件最快方法
  10. Mac 上安装MySQL