這裡提供一個Two pointer的解法,有興趣的讀者可以看一下!
感謝作者,讓我們認識leetcode的好XD
class Solution:
def calculateDigitSquaredSum(self, n : int) -> int:
s = 0
for c in str(n):
s += int(c) ** 2
return s
def isHappy(self, n: int) -> bool:
slow = fast = n
while True:
slow = self.calculateDigitSquaredSum(slow)
fast = self.calculateDigitSquaredSum(fast)
fast = self.calculateDigitSquaredSum(fast)
if slow == fast:
break
return fast == 1