![](https://img.haomeiwen.com/i14924385/d17000a29559145e.jpg)
LeetCode 202. Happy Number
Description
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:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
描述
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19
输出: true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
思路
- 两个辅助函数:divide函数将所有的一个数拆成单独的数字;square求所有数字的平方和.
- 我们用一个hash set 来记录已经出现过的结果,如果有一个结果已经出现过且不等于1返回Fasle,如果出现了1返回True.
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2019-01-20 21:06:07
# @Last Modified by: 何睿
# @Last Modified time: 2019-01-21 18:50:47
class Solution:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
numset = set()
newn = self.square(self.divide(n))
# 如果求和的结果没有出现过
while newn not in numset:
numset.add(newn)
newn = self.square(self.divide(newn))
# 如果等于1,返回True
if newn == 1: return True
# 若求和的结果已经出现且不等于1,返回False
return False
# 拆分函数,返回list
def divide(self, n):
res = []
while n:
res.append(n % 10)
n //= 10
return res
# 返回所有数子的平方和
def square(self, nums):
return sum([x**2 for x in nums])
网友评论