Back to course home
0% completed
Vote For New Content
Simpler solution
Luis Roel
Dec 9, 2024
def isHappy(self, n: int) -> bool: # The first sum is the inpout curr_sum = n # We keep track of cycles using a set seen = set() # The goal is to see if we can reach a sum # of 1 or, notice if we've seen a particular sum # before while curr_sum != 1 and curr_sum not in seen: # First, add current sum to our set before we change it seen.add(curr_sum) # Get the digits of current sum digits = [int(d) for d in str(curr_sum)] # Calculate new sum # (notice we're starting fresh, not adding to curr_sum) new_sum = 0 for digit in digits: # Square the current digit and # add it to the new sum new_sum += digit * digit # Update curr_sum with our new calculation curr_sum = new_sum # If by the time the loop break, the below is True # then we have a happy number, if its False, then # our number is unhappy return curr_sum == 1
0
0
Comments
Comments
On this page