编写一个算法来判断一个数 n
是不是快乐数。
「快乐数」定义为:
- 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
- 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
- 如果 可以变为 1,那么这个数就是快乐数。
如果 n
是快乐数就返回 true
;不是,则返回 false
。
示例 1:
输入:19 输出:true 解释: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
示例 2:
输入:n = 2 输出:false
示例代码1:[用哈希集合检测循环]
class Solution:
def isHappy(self, n: int) -> bool:
def get_next(n):
total_num = 0
while n > 0:
n, digit = divmod(n, 10)
total_num += digit ** 2
return total_num
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = get_next(n)
return n == 1
示例代码2:[快慢指针法]
class Solution:
def isHappy(self, n: int) -> bool:
def get_next(n):
total_num = 0
while n > 0:
n, digit = divmod(n, 10)
total_num += digit ** 2
return total_num
slow_runner = n
fast_runner = get_next(n)
while fast_runner != 1 and slow_runner != fast_runner:
slow_runner = get_next(slow_runner)
# fast_runner = get_next(slow_runner)
fast_runner = get_next(get_next(fast_runner)) # 这行代码比上面代码时间方面快了两倍
return fast_runner == 1
示例代码3:[数学]
class Solution:
def isHappy(self, n: int) -> bool:
def get_next(n):
total_num = 0
while n > 0:
n, digit = divmod(n, 10)
total_num += digit ** 2
return total_num
cycle_members = {4, 16, 37, 58, 89, 145, 42, 20}
while n != 1 and n not in cycle_members:
n = get_next(n)
return n == 1