Skip to content

Commit 4b4f1ab

Browse files
committed
happy数
1 parent 0d91074 commit 4b4f1ab

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

easy/202_Happy Number.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
3+
Write an algorithm to determine if a number is "happy".
4+
5+
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.
6+
7+
Example: 19 is a happy number
8+
9+
12 + 92 = 82
10+
82 + 22 = 68
11+
62 + 82 = 100
12+
12 + 02 + 02 = 1
13+
14+
15+
"""
16+
17+
18+
"""
19+
solution 1: floyid 检测是否有环的算法,如果能到1,则fast先到1,随后等待slow得到1,如果不会得到1,则fast会追上slow
20+
则此时存在圈,不会得到1
21+
"""
22+
23+
class Solution(object):
24+
def isHappy(self, n):
25+
"""
26+
:type n: int
27+
:rtype: bool
28+
"""
29+
slow = n
30+
fast = sum([int(x) ** 2 for x in str(n)])
31+
while fast != slow:
32+
slow = sum([int(x) ** 2 for x in str(slow)])
33+
fast = sum([int(x) ** 2 for x in str(fast)])
34+
fast = sum([int(x) ** 2 for x in str(fast)])
35+
return slow == 1
36+
37+
"""
38+
solution 2 : 使用一个set保存出现过的数字,如果某个数字已经在set中了,说明出现了环,判断此时的n是否为1即可
39+
"""
40+
class Solution(object):
41+
def isHappy(self, n):
42+
"""
43+
:type n: int
44+
:rtype: bool
45+
"""
46+
c = set()
47+
while not n in c:
48+
c.add(n)
49+
n = sum([int(x) ** 2 for x in str(n)])
50+
return n==1

0 commit comments

Comments
 (0)