Python recursion solution 83%

  • 0

    Run 3 times and the best one is 48ms 83%

    1. Conversion from int to list of digits is done by keeps divmod the
      number by 10.
    2. Every time after the sum of squares, make a check to see if we got number 1. If so, the original number is a happy number. if not, check if the result has been seen before. Getting a seen number means we are in a loop thus we return
    3. if we get a un-seen result, we just save it to the seen list and
      apply the function recursively to it.

    class Solution(object):
        def __init__(self):
            self.seen = []
        def isHappy(self, n):
            :type n: int
            :rtype: bool
            digi = []
            while n > 9:
                n, r = divmod(n, 10)
                if r != 0:
            new_n = sum(map(lambda x: x**2, digi))
            if new_n == 1:
                return True
            elif new_n in self.seen:
                return False
                return self.isHappy(new_n)

Log in to reply

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