-
Notifications
You must be signed in to change notification settings - Fork 0
/
202_happy_number.py
40 lines (33 loc) · 1.12 KB
/
202_happy_number.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
##########################################################################
# > File Name: 202_happy_number.py
# > Author: Tingjian Lau
# > Mail: [email protected]
# > Created Time: 2016/05/16
#########################################################################
class Solution(object):
def digitSquareSum(self, n):
return sum([int(i) ** 2 for i in str(n)]) # 注意此简练写法
# Floyd判圈算法
def isHappy_1(self, n):
"""
:type n: int
:rtype: bool
"""
slow, fast = n, self.digitSquareSum(n)
while slow != fast:
slow = self.digitSquareSum(slow)
fast = self.digitSquareSum(self.digitSquareSum(fast))
return slow is 1
# hash table法
def isHappy(self, n):
hashTable = set() # 申请一个无序无重复的集合
while n != 1:
n = self.digitSquareSum(n)
if n in hashTable:
return False
else:
hashTable.add(n)
else:
return True