Easy to Follow Python Solution

  • 0
        def isHappy(self, n):
        return self.isHappyHelper(n, {})
    def isHappyHelper(self, n, prev):
        if n == 1:
            return True
        elif n not in prev:
            prev[n] = 1
            return False
        new = 0
        for char in str(n):
            new += int(char)**2
        return self.isHappyHelper(new, prev)

    Recursive solution. To detect a cycle, use a dict to see if we've already seen the number. If we have, return False. If we haven't seen it, add it to the dictionary. If the number is 1, return True.

Log in to reply

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