Leetcode 202题 Happy Number
Write an algorithm to determine if a number n 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.
Return True if n is a happy number, and False if not.
Example:
Input: 19
Output: true
Explanation:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200513211450802.png)
题目大意:
判断一个数字是否是Happy的,什么数字是Happy呢?给你一个初始数字,用这个数字每位数的平方和来替代这个数字,重复这个过程,直到数字变为1。这个数字就叫做Happy数字。 如果落入无限循环,则返回False。
按照题意,直接循环计算各位上数字的平方和。
class Solution:
def isHappy(self, n: int) -> bool:
var = set()
while True:
nums = str(n)
temp = 0
for i in nums:
temp += int(i) ** 2
if temp in var:
return False
elif temp == 1:
return True
else:
var.add(temp)
n = temp
唯一可能出错的地方就是中间数据类型的转换,用str(n)方便循环遍历每一位数字, 再用int(i)是因为做平方运算必须得是int类型。
疫情中的英国,
加油!
13/05/2020