[Python-leetcode202- pointer speed] happy number

Problem 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: 

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Core: if not a happy number, it will enter circulation. Cyclic ring is equivalent problem, you can use a pointer speed. Computing a pointer to a slow, fast pointer calculation twice, when the meet cursor speed, into the cycle described, the number is not happy.

class Solution:
    def isHappy(self, n: int) -> bool:
        slow = str(n)
        fast = str(sum(int(i)**2 for i in str(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"

result:

 

Guess you like

Origin www.cnblogs.com/xiximayou/p/12342970.html