Leetcode 202. Happy Number
来源:互联网 发布:网络管理从入门到精通 编辑:程序博客网 时间:2024/06/06 07:25
202. 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
Credits:
Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution {public: int get(int x){ //得到下一个数 int temp=0; while(x){ temp+=(x%10)*(x%10); x/=10; } return temp; } bool isHappy(int n) { set<int>Q; Q.insert(n); while(1){ int t=get(n); if(t==1){ return true; } else{ if(Q.count(t)){ return false; } else{ Q.insert(t); } } n=t; } }};
出现1,返回true,如果出现循环, 则无需继续计算,直接返回false即可
1 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
- Android ProgressBar详解以及自定义
- hdu 5055(贪心)
- 1.2、开发工具——sublime篇
- JS小技巧:判断数据类型的一种方法
- JavaScript---网络编程(12)--DHTML技术演示(5)-form表单验证技术(正则)
- Leetcode 202. Happy Number
- Linux学习之帮助命令
- 怎么样在input标签选择是直接显示本地图片
- 虚析构函数(√)、纯虚析构函数(√)、虚构造函数(X)
- C语言基础 检查自己的编译器是否支持根据输入来确定数组的大小
- 改良用简单工厂模式构造的计算器代码—“反射”技术
- 虚拟机安装centos 7网络查看以及连接
- hdu 2159 二维完全背包
- Android - 回到顶部实现