LeetCode 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:

1
2
3
4
5
6
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,则是快乐数,否则不是。

  • 输入:一个整数
  • 条件:无
  • 任务:判断这个数是不是 happy number
  • 输出:True or False

代码

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
seen = set()
while n not in seen:
seen.add(n)
n = sum([int(x) **2 for x in str(n)])
return n == 1

点评

用一个集合记录当前所有计算出来的平方和,如果下一次计算出来的数在这个集合里,则退出循环,并判断这个数是不是 1