博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
202. Happy Number
阅读量:6995 次
发布时间:2019-06-27

本文共 927 字,大约阅读时间需要 3 分钟。

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: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

python实现:

class Solution(object):

    def sqrsum(self, n):#计算平方和
        m = 0
        while n:
            if n < 10:
                n1 = n
            else:
                n1 = n % 10
            m += n1 ** 2
            n = n / 10
        return m
       
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        LN:list of not happy
        tL:tempt list
        """
        LN = []
        tL = []
        while True:
            if n in LN:
                return False
            elif n not in tL:
                tL.append(n)
                n = self.sqrsum(n)
                if n == 1:
                    return True
            else:
                LN.extend(tL)

转载于:https://www.cnblogs.com/sxbjdl/p/5221571.html

你可能感兴趣的文章
Swift教程之属性
查看>>
动手动脑3
查看>>
HDU 3397 Sequence operation(线段树区间染色加区间合并)
查看>>
【随笔】写下现在所想的,开始写博客
查看>>
linux命令之vi文本编辑器
查看>>
WPF-WrapPanel
查看>>
大家好
查看>>
iOS 疑难杂症 — — UITableView 添加 tableFooterView 旋转屏幕后收不到点击事件!!!...
查看>>
asp.net 8 Request,Response,Server
查看>>
Windows API 技巧集
查看>>
github心得体会
查看>>
Binary Tree Level Order Traversal [LEETCODE]
查看>>
Install/uninstall .deb files
查看>>
如何让自己的代码更加安全?
查看>>
EBS_DBA_问题:关于不小心drop了表,进行恢复
查看>>
MongoDB数据库
查看>>
HDU-1875-畅通工程再续(最小生成树)
查看>>
POJ-1182-食物链(并查集种类)
查看>>
POJ1288 Sly Number(高斯消元 dfs枚举)
查看>>
Toping Kagglers:Bestfitting,目前世界排名第一
查看>>