In this series, I am going to solve Leetcode medium problems live with my friend, which you can see on our youtube channel, Today we will do Problem Problem 202. Happy Number.
A little bit about me, I have offers from Uber India and Amazon India in the past, and I am currently working for Booking.com in Amsterdam.
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.
n is a happy number, and
false if not.
Input: n = 19
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Input: n = 2
This is a basic recursion based problem. We need to replace a number with the sum of the square of its digits. We need to repeat this process until the number becomes 1 or it loops endlessly in a cycle. In the case of reaching 1, we should return true else false.
So to keep track of all the last encountered numbers we can use a HashSet and then we can keep checking if our current number is present in that HashSet or not. If it is present , then we immediately terminate the method and return false , else we keep on finding the sum of square of it’s digits.
The following is the Java code for the given problem.
The C++ code is given below.
The code for this problem can be found in the following repository.