【刷题-LeetCode】202. Happy Number
2024-09-05 12:40:23
- 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;
}
};
最新文章
- mapReduce的shuffle过程
- Java class file format specfication
- Verilog篇(二)系统函数
- DBCP参数介绍
- 5 commands to check memory usage on Linux
- oracle 更改SQL提示
- hql和sql的一些区别
- cf441 f组合数。。单调指针
- eclipse 安装合适的pydev插件
- Unity3D笔记 英保通一
- 20172311『Java程序设计』课程 结对编程练习_四则运算第一周阶段总结
- Java从零开始学二十九(大数操作(BigIntger、BigDecimal)
- Tomcat 7 可以修改 Session 默认的 Cookie 名 JSESSIONID 了
- LUA表 pairs, ipairs输出顺序问题
- helm 安装 spinnaker
- wfst讲解
- DESC和 ACS
- WCF身份验证三:自定义身份验证之<;MessageHeader>;
- Android四大组件:Service
- PAT L2-006【二叉树中序后序构造树】
热门文章
- 『学了就忘』Linux系统定时任务 — 88、循环执行定时任务
- action中redirectAction到另一个命名空间中的action该如何配置
- Centos 配置服务器
- jquery gantt 的使用
- Git统计代码变化率
- 【LeetCode】987. Vertical Order Traversal of a Binary Tree 解题报告(C++ & Python)
- 【LeetCode】698. Partition to K Equal Sum Subsets 解题报告(Python & C++)
- 1048 - Conquering Keokradong
- Codeforces 450D:Jzzhu and Cities(最短路,dijkstra)
- RotateRect(旋转矩形)的倾斜旋转变换矫正