202. 快乐数

编写一个算法来判断一个数是不是“快乐数”。

一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。

示例: 

输入: 19
输出: true
解释: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
class Solution:
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        num = n
        exist_nums = []
        while True:
            res = sum([int(x)**2 for x in list(str(num))])    
            num = res

            if res == 1:
                return True
            elif res in exist_nums:
                return False

            exist_nums.append(res)  // 存储中间结果,出现循环则判断不是快乐数
posted @ 2018-07-23 13:44  yuyin  阅读(61)  评论(0编辑  收藏  举报