2 concise python solutions + a little math


  • 0
    C

    1st solution, using set(), easy to understand

        def isHappy(self, n):
            happyset = set()
            while n > 1 and n not in happyset:
                happyset.add(n)
                n = sum(map(lambda x: int(x) ** 2, list(str(n))))
            return n == 1
    

    2nd solution, if n is not happy, it always falls into a cycle: 4, 16, 37, 58, 89, 145, 42, 20, 4, ..., that's math :). check https://en.wikipedia.org/wiki/Happy_number

        def isHappy(self, n):
            if n == 1:
                return True
            elif n == 4: # or any other number in the cycle, pick 42 if you like it, "42 is the answer"
                return False
            else:
                return self.isHappy(sum(map(lambda x: int(x) ** 2, list(str(n)))))
    

    Just one more minor comment about the running time: 72 ms for the 1st and 65 ms for the 2nd solution. I wrote another code with a helper function to calculate sum(map(lambda x: int(x) ** 2, list(str(n)))) in the 1st solution, and it only costs 42ms. It's ugly and long but it's faster.


Log in to reply
 

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