LeetCode 202. Happy Number 题解
来源:互联网 发布:厦门云智盛世 数据库 编辑:程序博客网 时间:2024/06/01 21:47
题目描述:
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
解题思路:
本题想法非常简单,即不停的迭代算下一次结果,看是不是满足数字之和为1。但是关键点在于如果该数字不是happy number,如何终止循环。此时考虑用一个map<int,bool>,,如果sum(所有数字的和)为1,则返回true。如果sum不为1,且为第一次出现,则将map[sum]的值置为true,意为该值已经出现过,如果之后再次出现相同的sum值,则说明此时该数陷入了一个循环,也即该数不是happy number,则返回false。
代码展示:
class Solution {public: bool isHappy(int n) { if(n==0) return false; map<int,bool> res; int sum =0; while(1) { while(n>0) { sum+=pow(n%10,2); n/=10; } if(sum==1) return true; if(!res[sum]) //判断sum之前是否出现过,若未出现过则标记为已出现,同时将n置为sum,将sum置为0,开始下一次迭代 { res[sum]=true; n = sum; sum=0; } else//如果出现过则说明此时陷入循环,不是happy number { return false; } } return false; }};
0 0
- LeetCode 202. Happy Number 题解
- LeetCode Happy Number 题解
- LeetCode题解:Happy Number
- LeetCode 题解(200) : 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
- 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
- 初学移动开发技术_实验二_任务二_标准体重计算器
- python 菜鸟成长记——搭建项目框架
- Android动态加载黑科技 动态创建Activity模式
- 我是如何利用GO实现Session技术
- 分布式多级服务器架构设计构思
- LeetCode 202. Happy Number 题解
- 2016/9/20已经结清的贷款解除卡号与贷款账号的关联关系
- 一定要知道的sublime使用技巧
- 面向对象_javadoc说明书的制作过程
- 系统架构
- Leetcode 315. Count of Smaller Numbers After Self[hard]
- pcap文件分析-下之winpcap编程入门
- 大数相加
- 并查集模板及对应模板题