https://leetcode-cn.com/problems/happy-number/solution/kuai-le-shu-by-leetcode-solution/
方法一:集合
class Solution:
def isHappy(self, n: int) -> bool:
if n < 0:
return False
seen = set()
while n not in seen:
seen.add(n)
nex = 0
for digit in str(n):
nex += int(digit) ** 2
if nex == 1:
return True
n = nex
return False
def isHappy(self, n: int) -> bool:
def get_next(n):
total_sum = 0
while n > 0:
n, digit = divmod(n, 10)
total_sum += digit ** 2
return total_sum
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = get_next(n)
return n == 1
方法二:双指针
class Solution:
def isHappy(self, n: int) -> bool:
def get_next(number):
total_sum = 0
while number > 0:
number, digit = divmod(number, 10)
total_sum += digit ** 2
return total_sum
slow = n
fast = get_next(n)
while fast != 1 and slow != fast:
slow = get_next(slow)
fast = get_next(get_next(fast))
return fast == 1
方法三:数学
class Solution:
def isHappy(self, n: int) -> bool:
nums = {4, 16, 37, 58, 89, 145, 42, 20}
def get_next(number):
total_sum = 0
while number > 0:
number, digit = divmod(number, 10)
total_sum += digit ** 2
return total_sum
while n != 1 and n not in nums:
n = get_next(n)
return n == 1