3

LeetCode 第202题 Happy Number

 3 years ago
source link: https://codechina.org/2019/08/leetcode-202-happy-number-java/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

来源:https://leetcode.com/problems/happy-number

题目:快乐数

写一个算法来确定一个数字是否“快乐”。

快乐数的定义如下:从任何正整数开始,用数的各位数字的平方的和来代替数字本身。然后一直重复这个过程知道数字等于1,或者它进入其他的死循环,不包括1。如果能得到1则是快乐数。

Example: 

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

我们首先定义一个函数split,它可以把一个数字的每个位分离出来,形成一个List。

split.png

然后我们定义一个函数combine,把一个List里面的全部数字的平方和算出来。

combine.png

然后,我们就不断的调用split和combine,只要数字大于1,我们就split它然后combine,然后看结果是不是1,不是继续split和combine。但是有的时候会遇到死循环,所以我们把这个流程中出现的结果都扔到一个hashset里面,如果发现有重复的,就说明我们开始循环了,那么就退出,返回false即可。而只要数字是1就返回成功。

main-3.png

Github:https://github.com/tinyfool/leetcode/tree/master/src/p0202

本题属于哈希表类题目,想了解更多关于哈希表的题目,可以参看哈希表专题

发表评论 取消回复

邮箱地址不会被公开。 必填项已用*标注

评论

姓名 *

电子邮件 *

站点

在此浏览器中保存我的姓名、电子邮件和站点地址。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK