Python 44ms, O(1) space


  • 8
    Y

    If you remember the solution of finding the cycle in linked-list, you can use same method : "Catch up!"

    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        r1 = self.step(n)
        r2 = self.step(r1)
        while(r1 != 1):
            if(r1 == r2):
                return False
            else:
                r1 = self.step(r1)
                r2 = self.step(self.step(r2))
        return True
    
    def step(self, n):
        result = 0
        while(n):
            result += pow(n % 10, 2)
            n = n // 10
        return result

  • 0
    N

    r2 = self.step(self.step(r2)) !!!


Log in to reply
 

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