一.问题描述
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and 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 numbers.
Example:
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
二.解题思路
判断是否是Happy Number:
如果每次每个位数平方求和,最后能以1结束,就是快乐数。
如果最后是个循环,就不是。
这道题其实就是考察分离每一个位数。
分离出每一位就是: n mod(%) 10, 就能把个位数分离出来。
然后 n=n/10 把n分离出来的个位数丢掉(其实是已经处理完了不需要了)。
当然你也可以把数字先转换成字符串,然后再对每个字符转换成数字,这样子就不用上面那个。
不过我觉得这样子应该很慢,你们可以试试,如果这样更快的话麻烦告诉我。
感觉这种简单的最好还是自己掌握比较好,毕竟,很多时候其他情况可能不能这样子取巧或者不适合用哪种方法。
至于考察是否是循环,用一个集合记录一下之前的每个n。发现现在的n已经在了就说明循环了。
题目比较简单,就要想想如何写的简介.(貌似我老是说这个)。
下面给出了两种实现,但是第二种快乐4ms至少,主要应该是if 语句减少了。判断放在while循环判断了。
更多leetcode算法题解法: 专栏 leetcode算法从零到结束
三.源码
# version 1
class Solution:
def isHappy(self, n: int) -> bool:
if n<0:return False
is_occured,nxt_n=set(),0
while True:
while n:
nxt_n+=(n%10)**2
n=int(n/10)
if nxt_n==1:break
if nxt_n in is_occured:break
else:is_occured.add(nxt_n)
n,nxt_n=nxt_n,0
return nxt_n==1
# version 2
class Solution:
def isHappy(self, n: int) -> bool:
if n<0:return False
is_occured,nxt_n=set(),0
while n not in is_occured and n!=1:
is_occured.add(n)
while n:
nxt_n+=(n%10)**2
n=int(n/10)
n,nxt_n=nxt_n,0
return n==1