Python solution with detailed explanation


  • 0
    G

    Solution

    Happy Number https://leetcode.com/problems/happy-number/

    Algorithm

    • Use a cache to store the previos generated numbers.
    • Generate the next number. If 1, return True. If in cache, then cycle and return False.
    class Solution(object):
        def helper(self, num):
            result = 0
            while num != 0:
                x = num % 10
                num = num / 10
                result += x*x
            return result
        
        def isHappy(self, n):
            """
            :type n: int
            :rtype: bool
            """
            cache = set([n])
            while True:
                n = self.helper(n)
                if n == 1:
                    return True
                elif n in cache:
                    return False
                else:
                    cache.add(n)
            return
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.