202. Happy Number python

Write an algorithm to determine whether a number is a "happy number".

The definition process of a happy number is as follows: starting from any positive integer, replace the original number with the sum of the squares of each digit, repeating this process will get two possibilities: 1. Number = 1 (at this time its value will no longer change ), 2. into an infinite loop that does not contain 1. Those numbers that end in 1 are "happy numbers".

Example: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1
class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        ans = set()
        while n != 1:
            n = sum(int(i)**2 for i in str(n))
            if n in ans:
                return False
            else:
                ans.add(n)
        else:
            return True


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324747494&siteId=291194637