[LeetCode] 202. happy number

Topic links: https://leetcode-cn.com/problems/happy-number/

Subject description:

Write an algorithm to determine if a number is not "count his joys."

A "happy number" is defined as: For a positive integer, each time replacing the squared number of its digits at each position and then repeat the process until the number becomes 1, it may be variable but has an infinite loop less than 1. If you can become one, then this number is the happy number.

Example:

输入: 19
输出: true
解释: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Ideas:

This question difficulty lies in how to solve the cycle repeats situation?

Note: I have here is a string sum, you can also use mathematical methods (modulo kind)

Method One: a hash record

class Solution:
    def isHappy(self, n: int) -> bool:
        n = str(n)
        visited = set()
        while 1:
            n = str(sum(int(i) ** 2 for i in n))
            if n == "1":
                return True
            if n in visited:
                return False
            visited.add(n)

Method two: speed (run)

class Solution:
    def isHappy(self, n: int) -> bool:
        n = str(n)
        slow = n
        fast = str(sum(int(i) ** 2 for i in n))
        while slow != fast:
            slow = str(sum(int(i) ** 2 for i in slow))
            fast = str(sum(int(i) ** 2 for i in fast))
            fast = str(sum(int(i) ** 2 for i in fast))
        return slow == "1"

Guess you like

Origin www.cnblogs.com/powercai/p/11370286.html