Skip to content

Commit

Permalink
更新 0202.快乐数.md python代码简化
Browse files Browse the repository at this point in the history
利用闭包的特性,修改了原本python代码中不符合PEP3的写法,以及赘余的代码。思路保持一致
  • Loading branch information
Eyjan-Huang authored Aug 16, 2021
1 parent 46c1084 commit fbeb80f
Showing 1 changed file with 20 additions and 16 deletions.
36 changes: 20 additions & 16 deletions problems/0202.快乐数.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,25 +111,29 @@ Python:
```python
class Solution:
def isHappy(self, n: int) -> bool:
set_ = set()
while 1:
sum_ = self.getSum(n)
if sum_ == 1:
def calculate_happy(num):
sum_ = 0

# 从个位开始依次取,平方求和
while num:
sum_ += (num % 10) ** 2
num = num // 10
return sum_

# 记录中间结果
record = set()

while True:
n = calculate_happy(n)
if n == 1:
return True
#如果这个sum曾经出现过,说明已经陷入了无限循环了,立刻return false
if sum_ in set_:

# 如果中间结果重复出现,说明陷入死循环了,该数不是快乐数
if n in record:
return False
else:
set_.add(sum_)
n = sum_

#取数值各个位上的单数之和
def getSum(self, n):
sum_ = 0
while n > 0:
sum_ += (n%10) * (n%10)
n //= 10
return sum_
record.add(n)

```

Go:
Expand Down

0 comments on commit fbeb80f

Please sign in to comment.