题目描述
确定某个数n是否是happy number。关于happy number的定义如下:
Starting with any positive integer, replace the number by the sum of the squares of its digits.
Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy.
意思就是不断用n的各个位上的数字的平方和代替原有的n,如果最终能回到1,那么这个数就是happy number, 如果最后陷入一个cycle,不包括1,那么这个数就是不是happy number。
读完题目,我有个疑惑,难道除了回到1和陷入cycle,就没有第三种情况了吗?难道不会产生无限不循环的情况越变越大吗?但是事实上,仔细思考之后就会发现这是不可能的。随便举个例子,比如原始的n是4位数中的最大值9999,那么它的下一步迭代值无非也就 9^2 * 4 = 324, 即使我们以9999作为开始,在接下来的步骤中,n只能在324以下的范围转悠,那么充其量经过324个迭代,最终还是会落入cycle的,其他位数的逻辑是一样的,即无限增大的情况是不可能存在的。所以唯一可能的情况就是陷入一个不包含1的循环,或者回到1。
解法1: Hash
想明白这个问题之后,我们就可以开始思考如何解决这个问题了。我的思路是使用hashmap。不断循环,并将已经出现的n保存在一个表中,如果出现的下一个值存在于存储表中(使用hash去索引), 且这时还没出现1,那么就意味这1再也不会出现了,这个值必然不是happy了。代码如下
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
n_history={}
while True:
try:
n_history[n]+=1
return False
except:
n_history[n]=0
digit_li=[str(n)[i] for i in range(len(str(n)))]
n=sum(list(map(lambda x:(int(x))**2,digit_li)))
if n==1:
return True
下面是官方的第一种解法,大致思路其实是一样的。
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
解法2: Floyd’s Cycle-Finding Algorithm
简单来说,我们设定两个变量,一个fast_runner,每次走两步,一个slow_runner,每次走一步。上面已经说了,这个迭代进行的过程最终只有两个结果,陷入cycle或者回到1。如果最终能够回到1,必然由fast_runner到达,如果陷入cycle,那么fast_runner 和 slow_runner会相遇。任意一种情况发生,我们让循环终止,接下来我们只需要判断终止时fast_runner的情况即可,如果为1,那么为happy number 否则就不是。代码如下:
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_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(get_next(fast_runner))
return fast_runner == 1