19.Happy Number-Leetcode
来源:互联网 发布:剑网三淘宝买金哪家 编辑:程序博客网 时间:2024/05/17 23:18
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
基本思路:
按照生成的思路写出相应代码,重点是考虑到循环何时跳出,此题若在
生成中间数的过程出现了重复,那一定会无休止的循环下去,便不是happy number,故用一个map来保存状态,暂未发现直接判断的方法
#define IMAX numeric_limits<int>::max()class Solution {public: bool isHappy(int n) { if(n<=0)return false; map<int,int> vis; //int num = pow(10,9); while(n!=1) { // num++; //if(num==IMAX)break; if(vis.count(n))return false;//出现重复的中间数 vis[n]=1; vector<int> vs; while(n) { vs.push_back(n%10); n=n/10; } n=0; for(int i=0;i<vs.size();++i)n=n+vs[i]*vs[i]; } return true; }};
0 0
- 19.Happy Number-Leetcode
- [leetcode] Happy Number
- leetcode: Happy Number
- [LeetCode] Happy Number
- [LeetCode]Happy Number
- LeetCode 202 Happy Number
- LeetCode OJ Happy Number
- [LeetCode]202.Happy Number
- LeetCode 202-Happy Number
- leetcode-202 Happy Number
- [LeetCode]Happy Number
- leetcode 202: Happy Number
- leetcode Happy Number
- [LeetCode 202]Happy Number
- LeetCode (24) Happy Number
- LeetCode Happy Number 题解
- [LeetCode] Happy Number
- leetcode 202 Happy Number
- 部分华为手机不显示logcat问题原因是手机底层开关没打开
- HDU 4192(中缀表达式转后缀表达式)
- 搭建struts2环境
- 如何学习
- HBase Coprocessor 剖析与编程实践
- 19.Happy Number-Leetcode
- A - 求奇数的乘积 Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Submit Sta
- 异步线程操作
- Android拍照
- vertex normal
- hibernate c3p0 连接无法释放 阻塞数据库操作
- git提交android项目 window8
- 第九周项目二 深复制函数(2)
- Java中StringBuffer类和String的区别