題目:
編寫一個算法來判斷一個數 n 是不是快樂數。
「快樂數」定義爲:對於一個正整數,每一次將該數替換爲它每個位置上的數字的平方和,然後重複這個過程直到這個數變爲 1,也可能是 無限循環 但始終變不到 1。如果 可以變爲 1,那麼這個數就是快樂數。
如果 n 是快樂數就返回 True ;不是,則返回 False 。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/happy-number
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
python3 解答
內存消耗:13.9 MB
1、想了一下,裏面的列表推導式,可以省略掉,會減少一部分內存;
2、遞歸調用,比較耗時,採用while循環,會減少運行時間;
class Solution:
def __init__(self):
self.__set = set()
def isHappy(self, n: int) -> bool:
str_num = str(n)
if n not in self.__set:
self.__set.add(n)
else:
return False
num = sum([int(_)**2 for _ in str_num])
print(num)
if num == 1:
return True
else:
print(str_num, n, 2222)
return self.isHappy(num)
優化後:
內存消耗:13.5 MB
class Solution:
def __init__(self):
self.__set = set()
def isHappy(self, n: int) -> bool:
if n not in self.__set:
self.__set.add(n)
else:
return False
num = 0
for _ in str(n):
num += int(_)**2
if num == 1:
return True
else:
return self.isHappy(num)
當然,還等有厲害的回答: 是從0-10以內尋找規律,只有4才能無限循環下去。(不是我想到的...)
class Solution:
def isHappy(self, n: int) -> bool:
while True:
n = sum(int(i) ** 2 for i in str(n))
if n == 4:
return False
if n == 1:
return True