[LeetCode] Top Interview 150 Problems Solving # 202 Happy Number
Understanding the Problem
Given a number a
as a parameter, each digit should be squared then sum every squared digits. Check if the sum of the squared digits is 1. If it has a value of 1, return True, if it loops infinitely, return False.
Approach
First I divided the digits into a list then squared each digit. I needed to check if this process is looping infinitely with a temporary memory as a list.
Solution
class Solution:
def isHappy(self, n: int) -> bool:
num = n
dup_list = []
while True:
calc_num = sum([int(i)**2 for i in str(num)])
if calc_num == 1:
return True
elif calc_num != 1 and calc_num not in dup_list:
dup_list.append(calc_num)
num = calc_num
else:
return False
It was very simple and the instruction was clear. I calculated the summed number then put the value into calc_num
. if the calc_num
is a value of 1, I return True. If calc_num
is not equal to 1 and it has not been shown yet during the loop, I keep this number in dup_list
to check if this number appears again. If it appears again, I return False.
Reflection
Easy peasy(?) or pissie or whatever. At this point I feel like I have come a little bit further with my coding skills and this kind of a problem looks easier than before, like before I began this blog. I was thinking about breaking the loop first to be safe but since it returns True and False anyways, I decided not to.