DEV Community

Ankan Bhattacharya
Ankan Bhattacharya

Posted on

Happy Number

Problem Statement

Write an algorithm to determine if a number n is 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.
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.
Return true if n is a happy number, and false if not.

Approach

  • First of all we need to check if the number is already 1. If it is so, return True.

  • Now if it is not so we dedicate a list of numbers to keep the track of the numbers that we already visited. If we visit them again, naturally we are in a loop and we cannot visit 1. Hence return False.

  • Else its obvious we will visit 1 and one we hit 1 return True.

Algorithm

Image description

Code

class Solution:
    def isHappy(self, n: int) -> bool: 
        #Check if the number is already 1 
        if n == 1: return True

        numArray: list[int] = []

        #Now loop through until the number becomes 1 or it is in numArray
        while n not in numArray:
            numArray.append(n)
            tempNum: int = 0

            while n > 0:
                tempNum += ((n%10) * (n%10))
                n //= 10

            if tempNum == 1: return True

            n = tempNum

        #If this statement hits, then it's a false
        return False
Enter fullscreen mode Exit fullscreen mode

Leetcode Result

Image description

So that's it... make sure if you liked the post and got to learn something, like the post and follow us. If you want me to improve at some point... leave that in the comment...

Top comments (0)