【LEETCODE】202-Happy Number

来源:互联网 发布:一号店在线客服软件 编辑:程序博客网 时间:2024/06/05 19:13

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

  • 1^2 + 9^2 = 82
  • 8^2 + 2^2 = 68
  • 6^2 + 8^2 = 100
  • 1^2 + 0^2 + 0^2 = 1

用哈希表记录每个出现过的sum,
当sum不是1并且再次出现的时候,说明进入循环,则返回false
当sum是1的时候,则返回true

class Solution(object):    def isHappy(self, n):        """        :type n: int        :rtype: bool        """                t=set()                          #定义一个哈希表                while n!=1 and n not in t:       #当n是1时,说明是happy,返回true,当n在t但不是1时,说明循环,返回false                        t.add(n)                     #将n加入哈希表里                        s=0                        while n!=0:                                a=n%10                s+=a*a                   #对每一位的数求平方,再加和                n=int(n/10)                        n=s                          #n变成最后的和s                return n==1                                            #if s not in t.key():                #t.add(s)                #n=s            #else:                #return False








0 0
原创粉丝点击