Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6763132

Browse files
committed
0202 Solved
1 parent c0bf7b8 commit 6763132

File tree

2 files changed

+103
-0
lines changed

2 files changed

+103
-0
lines changed

‎0202-happy-number/Animation/202.mp4‎

13.5 MB
Binary file not shown.
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# 202. 快乐数
2+
3+
> 本文首发于公众号「图解面试算法」,是 [图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>) 系列文章之一。
4+
>
5+
> 同步博客:https://www.algomooc.com
6+
7+
题目来源于 LeetCode 上 202 题,主要涉及**集合**。
8+
9+
## 题目
10+
11+
编写一个算法来判断一个数 n 是不是快乐数。
12+
13+
「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。
14+
15+
如果 n 是快乐数就返回 True ;不是,则返回 False 。
16+
17+
18+
19+
示例:
20+
21+
```
22+
输入:19
23+
输出:true
24+
解释:
25+
1^2 + 9^2 = 82
26+
8^2 + 2^2 = 68
27+
6^2 + 8^2 = 100
28+
1^2 + 0^2 + 0^2 = 1
29+
```
30+
31+
## 题目解析
32+
33+
我们先举一个例子
34+
35+
```
36+
输入: 59
37+
1. 5^2 + 9^2 = 106
38+
2. 1^2 + 0^2 + 6^2 = 37
39+
3. 3^2 + 7^2 = 58
40+
4. 5^2 + 8^2 = 89
41+
5. 8^2 + 9^2 = 145
42+
6. 1^2 + 4^2 + 5^2 = 42
43+
7. 4^2 + 2^2 = 20
44+
8. 2^2 + 0^2 = 4
45+
9. 4^2 = 16
46+
10. 1^2 + 6^2 = 37
47+
```
48+
49+
这个例子,我们可以看到输入59,第10步的结果和第2步一样,一直进行计算的话,会死循环,所以这个数肯定不会是快乐树。
50+
51+
那么会不会有结果一直无穷大的时候,理论上是不会的。
52+
53+
所以我们就会有两种情况,一种是计算后能得到1的,还有就是进入循环的。
54+
55+
56+
1. 创建Set
57+
2. 循环条件为当前值不为1,循环计算结果,并对每次结果进行判断
58+
3. 在Set里出现的,那么说明循环了,所以不会是快乐数,返回false
59+
4. 没在Set里出现的,那么将当前值存入Set中
60+
5. 循环结束,说明计算结果为1,所以return true
61+
62+
63+
64+
65+
## 动画理解
66+
67+
68+
<video id="video" controls="" preload="none" >
69+
<source id="mp4" src="../Animation/202.mp4" type="video/mp4">
70+
</video>
71+
72+
## 参考代码
73+
74+
75+
```javaScript
76+
/**
77+
* @param {number} n
78+
* @return {boolean}
79+
*/
80+
81+
var isHappy = function(n) {
82+
let set= new Set()
83+
let sum = 0
84+
n += ''
85+
while (sum !== 1) {
86+
sum = 0
87+
for (let i = 0; i < n.length; i++) {
88+
sum += n[i]*n[i]
89+
}
90+
n = sum + ''
91+
if (set.has(sum)) return false
92+
set.add(sum)
93+
}
94+
return true
95+
};
96+
```
97+
98+
## 复杂度分析
99+
100+
时间复杂度为O(logn),空间复杂度为O(logn)
101+
102+
103+
![](../../Pictures/qrcode.jpg)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /