Leetcode 202 — Happy Number
STOP stringifying numbers just to process the individual digits. Please, for the love of God.
In the last month I encountered multiple algorithmic tasks which involved the processing of individual digits in a number. And I found out a very common solution is to stringify the number and then process the letters as the separate digits. So I thought I’d share a better approach.
Leetcode Example
This is the assignment of Leetcode 202 problem, also called Happy Number.
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.
Now I found this solution on Youtube: Google LOVES this coding interview question. It’s in Python and it goes something like this:
def isHappy(n: int) -> bool:
seen = set()
current = str(n)
while current not in seen:
seen.add(current)
sum = 0
for digit in…