DEV Community

tomasmor42
tomasmor42

Posted on

Leetcode marathon day 2

The task of the second day is the task of finding a happy number:

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. Those numbers for which this process ends in 1 are happy numbers.

First I was thinking (as usual) to try to implement it straightforwardly. Let's create a function that gives us the next iteration for a number:

    def square_sum(n):
        return sum([int(i)**2 for i in str(n)])

At first, I was thinking that if we have a number with one digit it would be the end of the calculations and implemented it like this:

class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n < 10:
            return (n == 1)
        else:
            res = self.square_sum(n)
            return self.isHappy(res)

But quite fast I realised that this is not correct. Because if we have 7, for example, we will receive on the next step 49, which is not one digit.
But if we take another number as a threshold, like 3, it might work. But we actually don't need 3 only because 3^2 = 9 which is a one-digit number. We could use a higher threshold if it's not a happy number. And the lowest happy number is 7. So the final version is

class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n < 7:
            return (n == 1)
        else:
            res = self.square_sum(n)
            return self.isHappy(res)

It's not in any way an optimal solution, but it's working and according to the benchmarks it's working pretty well.

Top comments (0)