leetcode------Happy Number

标题: Happy Number
通过率: 34.3%
难度: 简单

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

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

用一个list去记录数字是否存在过,然后一直循环,只会出现两种情况,要么在list中出现过,要等于1,直接看代码:

 1 class Solution:
 2     # @presaram {integer} n
 3     # @return {boolean}
 4     def isHappy(self, n):
 5         map=[]
 6         while True:
 7             map.append(n)
 8             n=self.divideNum(n)
 9             if n==1:return True
10             elif n in map:return False
11     
12     def divideNum(self,n):
13         res=0
14         while n/10 != 0:
15             res=res+int(math.pow(n%10,2))
16             n=n/10
17         res=res+int(math.pow(n,2))
18         return res
19             
20             

 

posted @ 2015-04-23 15:33  pku_smile  阅读(106)  评论(0编辑  收藏  举报