leetcode-Happy Number
来源:互联网 发布:杨幂为李易峰打胎知乎 编辑:程序博客网 时间:2024/06/05 15:02
Question:
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
Solution:
class Solution { public: bool isHappy(int n) { if(n == 0){ return false; } n = getNum(n); unordered_set<int> mset; while(mset.insert(n).second){ if(n == 1){ return true; } n = getNum(n); } return false; } int getNum(int n){ int res = 0; while(n){ int tmp = n % 10; res += tmp * tmp; n /= 10; } return res; }};
总结:
unordered_set的函数insert返回值中各个版本都不一致:
(1)
pair
0 0
- [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
- LeetCode Happy Number
- MST最小生成树 Kruskal算法
- HDU-1083 Courses(匈牙利算法)
- Longest Substring Without Repeating Characters
- C++调用函数是如何返回临时对象的
- linuxmint18/ubuntu16.04LTS上搭建cocos2d-x-3.14.1安卓开发环境
- leetcode-Happy Number
- Linux内核 hlist_head/hlist_node结构解析
- 单例的创建
- [Codeforces600E]Lomsat gelral(dsu on the tree)
- 二叉树的定义和用Java进行实现
- 市场营销管理:如何慧眼识”千里马“?
- Struts功能详解——ActionForm
- CentOS&Redhat Linux常用命令,更新中......
- shell脚本放到crontab里就执行不成功的问题