Leetcode Happy Number Python 计算数字每一位的平方和 | str()为了遍历每一位,再int()回来是为了数学计算

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值