lintcode python代码 488 快乐数

来源:互联网 发布:日本媳妇 知乎 编辑:程序博客网 时间:2024/06/05 07:10

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

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

思路:先求各个位置上的数字 求余 得到个位数
while n != 0:
temp = n % 10
result += pow(temp, 2)
n = (n - temp) / 10
相加判断是否为1

class Solution:    # @param {int} n an integer    # @return {boolean} true if this is a happy number or false    def isHappy(self, n):        # Write your code her        record = set()        while True:            record.add(n)            n = self.Next(n)            if n == 1:                return True            elif n in record:                return False    def Next(self, n):        result = 0        while n != 0:            temp = n % 10            result += pow(temp, 2)            n = (n - temp) / 10        return result
原创粉丝点击