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.
Return True if
n
is a happy number, and False if not.Example:
Input: 19Output: trueExplanation:12 + 92 = 8282 + 22 = 6862 + 82 = 10012 + 02 + 02 = 1
Solution :
Intuition behind this problem is to keep replacing the numbers by their sum of square of their digits. Ex- for 45 can be replaced by (4^2 + 5^2 = 49). Now this 49 can be replaced by (4^2 + 9^2 = 97) and so on. till the number becomes 1.
But for some numbers like 4, it never comes down to 1, but it enters an infinite loop if we repeat the above process.
Here is a solution video for the whole intuition and explanation for this question.
Here is the complete code for different approaches :
Feel free to ask questions and share solutions that you used to solve the problem.