Solution with string conversion in python.


  • 8
    G

    In python, we can use the string---int conversion to solve this problem.

    class Solution:
        # @param {integer} n
        # @return {boolean}
        def isHappy(self, n):
            m = n
            mem = set()
                while m not in mem:
                mem.add(m)
                m = sum([int(x) ** 2 for x in str(m)])
                if m == 1:
                    return True
            return False

  • 0
    Z
    class Solution:
        # @param {integer} n
        # @return {boolean}
        def isHappy(self, n):
            i = 0 
            while i < 8  :
                sum = 0 
                for x in list(str(n)):
                    sum = sum + int(x)**2 
                n = sum 
                i = i + 1 
            if n ==1 :
                return True    
                    
            else: 
                return False
    

  • 0
    C

    excuse me but why " i<8" ? how do u come up with i <8 times? thank you!


Log in to reply
 

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