Update 0202.快乐数.md

This commit is contained in:
jianghongcheng
2023-05-05 20:25:46 -05:00
committed by GitHub
parent 3065cf3860
commit eeae3282a8

View File

@ -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 {