Write an algorithm to determine if a number
n is happy.A happy number is a number defined by the following process:
1.Starting with any positive integer, replace the number by the sum of the squares of its digits.
2.Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
3.Those numbers for which this process ends in 1 are happy.
Input: n = 19
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
A very interesting leetcode problem,i need to take some help from google for solving this problem. Here the catch was how to handle the non-happy number which never converge to 1.For this we used a set data structure which hold unique values in it. Let move towards the code.
First we will declare a set named “seen” and then start iteration using a while loop. In while loop we will check whether the number is not equal to 1 and the number is not present in the set. if the condition statisfy the while loop will start and add the “n” number in the set and then we will split the number and square each digits of the splitted number and add them but for splitting we will need to type cast it to string and then again type casted it to int after the split.
def isHappy(self, n: int) -> bool:
while n!=1 and n not in seen:
return not n in seen
The while loop will keep on running till n=1 or the number is present in the set. If it is a happy number the while loop will exit as the first condition is not satisfied and the number will not be in set and if its not a happy number then the while loop will exit as 2nd condition will not satisfy if number is present in the set. In the end we will return true of false depending on “n” is not in “seen” set.
“The only mistake you can make is not asking for help.”,this quote follow well for this leetcode problem there is not harm in asking for help in my case help is googling.So keep moving and keep coding…(cheers:-PN)