202. Happy Number

题目:

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: 19 is a happy number

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

快乐数的定义过程如下:从任意一个正整数开始,将原数替换为其每一位的平方和,重复此过程直到数字=1(此时其值将不再变化),或者进入一个不包含1的无限循环。那些以1为过程终止的数字即为“快乐数”。

思路:

  1. 数字转换字符(强制类型转换切片\对10求余)
  2. 平方和,结果记录,之后每次循环进行比较
  3. 返回结果 (出现1\出现重复循环)

解答:

初始答案 Time Limit Exceeded
原因是题目没有理解清楚,
题目中的循环不是指再次出现初始的n,
而是运算过程中的任一个结果循环出现

class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        num = n
        while True :
            if 1 == num:
                return True
            num = reduce(lambda x,y:int(x)*int(x)+int(y)*int(y),str(num))
            if n == num:
                return False

修改后

class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        num = n
        setnum = set()
        while True :
            num = sum(int(x)**2 for x in str(num))
            if 1 == num:
                return True
            if num in setnum:
                return False
            setnum.add(num)
posted @ 2016-09-25 20:44  Salmd  阅读(109)  评论(0)    收藏  举报