My python solution, 48ms


  • 0
    M
    class Solution(object):
        
        Happy = set([1])
        NotHappy = set()
        Temp = set()
        
        def isHappy(self, n):
            """
            :type n: int
            :rtype: bool
            """
            if n in self.Happy:
                self.Temp.clear()
                return True
            elif n in self.NotHappy:
                self.Temp.clear()
                return False
            else:
                self.Temp.add(n)
                result = 0
                div, mod = divmod(n, 10)
                result += mod*mod
                while div >= 10:
                    div, mod = divmod(div, 10)
                    result += mod*mod
                result += div*div
                if result == 1:
                    self.Happy.update(self.Temp)
                    self.Temp.clear()
                    return True
                elif result in self.Temp:
                    self.NotHappy.update(self.Temp)
                    self.Temp.clear()
                    return False
                else:
                    return self.isHappy(result)

Log in to reply
 

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