【Leetcode】刷题记之happy number
来源:互联网 发布:该怎么写淘宝店铺介绍 编辑:程序博客网 时间:2024/04/29 16:06
Total Accepted: 42546 Total Submissions: 124590 Difficulty: Easy
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
代码:
class Solution {public: bool isHappy(int n) { unordered_map<int,bool>sum_map;//使用STL的无序图存中间生成的和,便于确定会不会进入循环 int sum=helper(n);//求digits的平方和函数 while(sum!=1) {if (sum_map[sum]==true) return false; else {sum_map[sum]=true; sum=helper(sum);} } return true; } int helper(int m) { int sum=0; while(m>0) {sum+=(m%10)*(m%10); m=m/10; } return sum; }};注意:
1.如果出现循环,则为false。对于判断是否进入循环,可以用哈希容器unordered_map,存储已经出现过的平方和。无序图的使用详见点击打开链接
是时候复习一下数据结构了。。
2.还有一个问题,平方和,在没有引用cmath的时候,应该写成m*m,而不是m^2,这个是Matlab的语法。
anyway,keep on going!
0 0
- 【Leetcode】刷题记之happy number
- LeetCode之Happy Number
- leetcode之happy number
- leetcode之Happy Number
- LeetCode之Happy Number
- 开始刷leetcode: Happy Number
- [LeetCode刷题记录]Single Number II
- [LeetCode刷题记录]Number of Islands
- 【LeetCode刷题记录】Single Number
- 【LeetCode刷题记录】9. Palindrome Number
- LeetCode OJ 之 Happy Number (happy数)
- LeetCode之旅(18)-Happy Number
- [leetcode] Happy Number
- leetcode: Happy Number
- [LeetCode] Happy Number
- [LeetCode]Happy Number
- LeetCode 202 Happy Number
- LeetCode OJ Happy Number
- 20151123 ocp 052(10-30)
- 为了相同的前缀-北京热身复仇
- 怎么利用HttpURLConnection向服务器发送键值对
- 为了相同的前缀-公式计算
- 解决Volley框架下JsonObjectRequest以POST提交数据,服务端无法获取数据的问题。
- 【Leetcode】刷题记之happy number
- 运行地址,链接地址,加载地址,存储地址 位置无关码、位置有关码
- 重拾 hadoop mapreduce 学习 一
- 2015年11月23日19:17:54
- 为了相同的前缀-麦迪时刻
- Java基础——Java笔记——代码块
- 数三角形
- dbcp数据源加密
- android的消息处理机制(图+源码分析)——Looper,Handler,Message