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:
Input: 19 Output: true Explanation: 1^2 + 9^2 = 82 8^2 + 2^2 = 68 6^2 + 8^2 = 100 1^2 + 0^2 + 0^2 = 1
思路: 采用递归思想 需要找出数字中的每一位
出现问题:
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
s = 0
for c in str(n):
s += int(c)**2
print(s)
if s == 1:
return True
else:
self.isHappy(s)
if __name__ == "__main__":
n = Solution().isHappy(19)
print(n)
网上思路: https://blog.csdn.net/coder_orz/article/details/51315486
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
num__dict = {}
while True:
num__dict[n] = True
sum = 0
while n>0:
sum += (n%10) ** 2
n = n // 10
if sum == 1:
return True
elif sum in num__dict:
return False
else:
n = sum
if __name__ == "__main__":
n = Solution().isHappy(19)
print(n)