Happy Number with Python and Javascript

Created on Aug 29, 2020
Updated on Sep 28, 2020

Happy number is a medium leetcode problem, please invest some time in understanding the problem at leetcode.

How to Approach such Problem

If we go for a recursive approach, we need a base case .. what if we have 10


so in this case, we will get 1 .. what if we have 13, well that means we need to sum the square of 1 and the square of 3 which will add up to 10 which can get us to the base case

$$1^2 + 3^2 = 10$$

$$1^2 + 0^2 = 1$$

So we need a way to get each digit separately and square that digit and then sum the two .. we can get the right number (digit) by calculating the remainder and we can get the left number (digit) by integer division

But there is a probability to see more than two-digit number, so we need to consider each digit in that number and loop through it which can be done by seeing this number as a string which we can loop through

Here is my implementations in Python and Javascript:



Other problem-solving stuff

If you want to see more problem-solving blog posts, check out: