2 methods in python : use set and use cycle detect algorithm


  • 1
    G
    class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        x = set()
        a = b = n
        while(True):
            string = str(a)
            x = 0
            for c in string:
                x += int(c)**2
            a = x
            
            string = str(b)
            y = 0
            for c in string:
                y += int(c)**2
            b = y
            
            string = str(b)
            y = 0
            for c in string:
                y += int(c)**2
            b = y
    
            if (x ==y and x!=1):
                return False
            if (x==y and x==1):
                return True
    
    class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        x = set()
        while(True):
            string = str(n)
            res = 0
            for c in string:
                #print(int(c))
                res += int(c)**2
            if (res==1):
                return True
            elif (res in x):
                return False
            else :
                x.add(res)
                n=res

Log in to reply
 

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