LeetCode: Happy Numbers

Solving "Happy Numbers" from LeetCode in python

Posted by Asa Hess-Matsumoto on Tuesday, August 11, 2020
Last Modified on Monday, August 24, 2020

For this LeetCode problem, the goal was to write an algorithm to determine if a given number n was “happy”. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Thos numbers for which this process ends in 1 are happy numbers. The algorithm returns True if n is a happy number and False if not.

This was one of the more simple problems. Essentially I create a while loop that runs a process until the number it is handling is 1 (in which case, return True) or it sees a number it has already worked on. I had numbers that were worked on added to a list.

In retrospect, one way I could make this algorithm faster would be to use a hashmap, rather than rely on python’s keyword in. This could require a fair bit of memory, depending on the values that are generated.

class Solution:
    def isHappy(self, n: int) -> bool:
        
        number = n
        
        #Create list of numbers processed thus far:
        nums = []
        
        while number not in nums:
            
            #base case
            if number == 1:
                return True
            
            nums.append(number)
            
            #split up the integer
            strList = list(str(number))
            
            #create a sum total of each digit-squared
            number = sum(int(num)**2 for num in strList)
            
        return False