Simple Python Solution


  • 3
    M
    class Solution(object):
    
        def isHappy(self, n):
            """
            :type n: int
            :rtype: bool
            """
            s = set()
            while n != 1:
                if n in s:
                    return False
                s.add(n)
                n = sum([int(i) ** 2 for i in str(n)])
            return True

  • -1

    和我想得一模一样,这是我写的代码,

    class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        tmp=self.sq(n)
        s=set()
        while tmp!=1:
        	if tmp not in s:
        	    s.add(tmp)
        	    tmp=self.sq(tmp)
        	else:
        		return False
    
        return True
    
        
    
    def sq(self, num):
    	a=[ord(x)-ord('0') for x in str(num)]
        sum =0
        for x in a:
        	sum+=x**2
        return sum
    

Log in to reply
 

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