My solution: Python DFS method and Iterative. Simple ans easy


  • 0
    O
    1. dfs method:
    def isHappy(self, n):
        d= {}
        def dfs(n):
    	if n==1: return True
    	if n in d: return False
    	d[n]=True
    	a = list(str(n))
    	c = sum(map(lambda x: int(x)**2,a))
    	return dfs(c)
        return dfs(n)
    
    1. iterative:
    def isHappy(self, n):
        d= {}
        while n!=1 and n not in d:
        d[n]=True
        a = list(str(n))
        n = sum(map(lambda x:int(x)**2,a))
        return n==1
    

Log in to reply
 

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