leetcode happy number

来源:互联网 发布:linux命令 cp r 编辑:程序博客网 时间:2024/05/01 02:44

https://leetcode.com/problems/happy-number/


记住如何从integer里面提取 digit,


while n:d = n % 10res.append(d)n /= 10


set 是用set()初始化而用add 更新的只要平方和的结果有重复,而且重复的不是1,那么就是false。参考http://bookshadow.com/weblog/2015/04/22/leetcode-happy-number/


class Solution(object):    def isHappy(self, n):        """        :type n: int        :rtype: bool        """                if n <=0 :            return False                record = set()                while n not in record:            record.add(n)            sum = 0            while n:                d = n%10                sum += d * d                n /= 10            if sum == 1:                return True            else:                n = sum        return False







0 0