Happy Number in Python


Here we will see how to detect a number n is one Happy number or not. So the happy number is a number, where starting with any positive integers replace the number by the sum of squares of its digits, this process will be repeated until it becomes 1, otherwise it will loop endlessly in a cycle. Those numbers, when the 1 has found, they will be happy number.

Suppose the number is 19, the output will be true as the number is happy number. As we can see from 19, we will get

12 + 92 = 82

82 + 22 = 68

62 + 82 = 100

12 + 02 + 02 = 1

To solve this, we will follow these steps −

  • Here we will use the dynamic programming approach, and solve this using recursion
  • Base case is, when n = 1, then return true
  • When n is already visited, return false
  • mark n as visited
  • n := n as string, l := list of all digits in n
  • temp := squared sum of all digits
  • return function recursively with parameter temp and visited list

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def isHappy(self, n):
      """
      :type n: int
      :rtype: bool
      """
      return self.solve(n,{})
   def solve(self,n,visited):
      if n == 1:
         return True
      if n in visited:
         return False
      visited[n]= 1
      n = str(n)
      l = list(n)
      l = list(map(int,l))
      temp = 0
      for i in l:
         temp += (i**2)
      return self.solve(temp,visited)

Input

19

Output

true
raja
Published on 16-Jan-2020 10:17:50
Advertisements