LeetCode 202. Happy Number
来源:互联网 发布:萨勒曼 知乎 编辑:程序博客网 时间:2024/06/07 09:40
Happy Number
题目描述:
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
题目思路:
第一种方法,通过递归一只算下去,用数组记录已经出现的数字,如果在递归过程中算出的数字是重复,那么就结束递归过程。然后判断元素1是否出现即可。
第二种方法,是快慢指针判断链表是否存在环。引申过来如果快慢指针相遇,判断是否是1即可。
题目代码:
class Solution {public: int vis[999] = {0}; bool isHappy(int n) { int t = 0; while(n){ t += (n%10) * (n%10); n/=10; } dfs(t); if(vis[1]) return true; return false; } void dfs(int n){ int res = 0; while(n){ res += (n%10) * (n%10); n/=10; } if(vis[res]){ return ; } vis[res] = 1; dfs(res); }};
class Solution {public: bool isHappy(int n) { int pf, ps; ps = num(n); pf = num(ps); while(pf != ps){ ps = num(ps); pf = num(pf); pf = num(pf); } return ps == 1; } int num(int n){ int res = 0; while(n){ res += (n%10)*(n%10); n /= 10; } return res; } };
阅读全文
0 0
- [LeetCode]202.Happy Number
- 【LeetCode】202.happy number
- LeetCode 202. Happy Number
- [leetcode] 202.Happy Number
- 【leetcode】202. Happy Number
- [leetcode] 202. Happy Number
- 202. Happy Number LeetCode
- leetCode 202. Happy Number
- [LeetCode]202. Happy Number
- leetcode 202. Happy Number
- leetcode 202. Happy Number
- LeetCode *** 202. Happy Number
- leetcode 202. Happy Number
- leetcode 202. Happy Number
- LeetCode 202. Happy Number
- leetcode 202. Happy Number
- #leetcode#202. Happy Number
- leetcode-202. Happy Number
- STM32F103至STM32F407程序移植参考
- Python网络爬虫反爬破解策略实战
- Map排序
- Okhttp3参数和文件同时上传
- mongodb 安全配置
- LeetCode 202. Happy Number
- 关于兼容性问题
- Android Camera API 2使用OpenGL ES 2.0和GLSurfaceView对预览进行实时二次处理(黑白滤镜)
- 博弈知识汇总
- MySQL中alter的用法
- Spring Ldap开发示例
- CMSampleBufferRef与byte*互相转换
- 在Myeclipse部署Tomcat时只有WEB-INF文件夹,无页面的及其他文件
- UdpClient的Available属性