1. Happy Number

Write an algorithm to determine if a number n 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.

Return True if n is a happy number, and False if not.

Example:

Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

对于happy number的操作,最终的结局可能是:

  • 收敛到1
  • 陷入循环
  • n不断增大直到无穷大

但是第三种情况肯定不会发生

Digits Largest Next
1 9 81
2 99 162
3 999 243
4 9999 324
13 9999999999999 1053

从表中可以看出,三位数最大的下一位是243,四位数最大的下一位小于999,因此最终也会小于243

解1 hashset判断是否出现环

class Solution {
public:
bool isHappy(int n) {
unordered_map<int, bool>mp;
while(!mp[n]){
mp[n] = true;
n = happy(n);
if(n == 1)return true;
}
return false;
}
int happy(int n){
int res = 0;
while(n){
int tmp = n % 10;
res += tmp * tmp;
n /= 10;
}
return res;
}
};

解2 Floyd环检测算法(龟兔赛跑)

class Solution {
public:
unordered_map<int, int>mp;
bool isHappy(int n) {
int faster = happy(happy(n)), slower = happy(n);
while(faster != 1 && faster != slower){
faster = happy(happy(faster));
slower = happy(slower); }
return faster == 1;
}
int happy(int n){
if(mp[n])return mp[n];
int res = 0;
while(n){
int tmp = n % 10;
res += tmp * tmp;
n /= 10;
}
return mp[n] = res;
}
};

最新文章

  1. mapReduce的shuffle过程
  2. Java class file format specfication
  3. Verilog篇(二)系统函数
  4. DBCP参数介绍
  5. 5 commands to check memory usage on Linux
  6. oracle 更改SQL提示
  7. hql和sql的一些区别
  8. cf441 f组合数。。单调指针
  9. eclipse 安装合适的pydev插件
  10. Unity3D笔记 英保通一
  11. 20172311『Java程序设计』课程 结对编程练习_四则运算第一周阶段总结
  12. Java从零开始学二十九(大数操作(BigIntger、BigDecimal)
  13. Tomcat 7 可以修改 Session 默认的 Cookie 名 JSESSIONID 了
  14. LUA表 pairs, ipairs输出顺序问题
  15. helm 安装 spinnaker
  16. wfst讲解
  17. DESC和 ACS
  18. WCF身份验证三:自定义身份验证之&lt;MessageHeader&gt;
  19. Android四大组件:Service
  20. PAT L2-006【二叉树中序后序构造树】

热门文章

  1. 『学了就忘』Linux系统定时任务 — 88、循环执行定时任务
  2. action中redirectAction到另一个命名空间中的action该如何配置
  3. Centos 配置服务器
  4. jquery gantt 的使用
  5. Git统计代码变化率
  6. 【LeetCode】987. Vertical Order Traversal of a Binary Tree 解题报告(C++ & Python)
  7. 【LeetCode】698. Partition to K Equal Sum Subsets 解题报告(Python & C++)
  8. 1048 - Conquering Keokradong
  9. Codeforces 450D:Jzzhu and Cities(最短路,dijkstra)
  10. RotateRect(旋转矩形)的倾斜旋转变换矫正