From 4fc751affb0fba096c9263256555d59aa82615aa Mon Sep 17 00:00:00 2001 From: Baturu <45113401+z80160280@users.noreply.github.com> Date: Mon, 31 May 2021 18:42:19 -0700 Subject: [PATCH] =?UTF-8?q?Update=200202.=E5=BF=AB=E4=B9=90=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0202.快乐数.md | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index c07405ec..999e7d52 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -108,7 +108,29 @@ class Solution { ``` Python: - +```python +class Solution: + def isHappy(self, n: int) -> bool: + set_ = set() + while 1: + sum_ = self.getSum(n) + if sum_ == 1: + return True + #如果这个sum曾经出现过,说明已经陷入了无限循环了,立刻return false + if sum_ in set_: + 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_ +``` Go: