From eeae3282a87c334f726fc3c8cd5dabd5b71c4612 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 20:25:46 -0500 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 | 96 ++++++++++++++++++++++++++++++-------- 1 file changed, 76 insertions(+), 20 deletions(-) diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index 5ac29e86..7fe8cd8d 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -108,23 +108,14 @@ class Solution { ``` Python: +(版本一)使用集合 ```python class Solution: - def isHappy(self, n: int) -> bool: - def calculate_happy(num): - sum_ = 0 - - # 从个位开始依次取,平方求和 - while num: - sum_ += (num % 10) ** 2 - num = num // 10 - return sum_ - - # 记录中间结果 + def isHappy(self, n: int) -> bool: record = set() while True: - n = calculate_happy(n) + n = self.get_sum(n) if n == 1: return True @@ -134,21 +125,86 @@ class Solution: else: record.add(n) -# python的另一种写法 - 通过字符串来计算各位平方和 + def get_sum(self,n: int) -> int: + new_num = 0 + while n: + n, r = divmod(n, 10) + new_num += r ** 2 + return new_num + ``` + (版本二)使用集合 + ```python +class Solution: + def isHappy(self, n: int) -> bool: + record = set() + while n not in record: + record.add(n) + new_num = 0 + n_str = str(n) + for i in n_str: + new_num+=int(i)**2 + if new_num==1: return True + else: n = new_num + return False +``` + (版本三)使用数组 + ```python class Solution: def isHappy(self, n: int) -> bool: record = [] while n not in record: record.append(n) - newn = 0 - nn = str(n) - for i in nn: - newn+=int(i)**2 - if newn==1: return True - n = newn + new_num = 0 + n_str = str(n) + for i in n_str: + new_num+=int(i)**2 + if new_num==1: return True + else: n = new_num return False ``` - + (版本四)使用快慢指针 + ```python +class Solution: + def isHappy(self, n: int) -> bool: + slow = n + fast = n + while self.get_sum(fast) != 1 and self.get_sum(self.get_sum(fast)): + slow = self.get_sum(slow) + fast = self.get_sum(self.get_sum(fast)) + if slow == fast: + return False + return True + def get_sum(self,n: int) -> int: + new_num = 0 + while n: + n, r = divmod(n, 10) + new_num += r ** 2 + return new_num +``` + (版本五)使用集合+精简 + ```python +class Solution: + def isHappy(self, n: int) -> bool: + seen = set() + while n != 1: + n = sum(int(i) ** 2 for i in str(n)) + if n in seen: + return False + seen.add(n) + return True +``` + (版本六)使用数组+精简 + ```python +class Solution: + def isHappy(self, n: int) -> bool: + seen = [] + while n != 1: + n = sum(int(i) ** 2 for i in str(n)) + if n in seen: + return False + seen.append(n) + return True +``` Go: ```go func isHappy(n int) bool {