Solve Leetcode Problems and Get Offers From Your Dream Companies | Problem 202. Happy Number(Easy)
Start writiProblem 202. Happy Number (Leetcode Easy)
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.
Motivation to Learn Algorithms
Problem Statement
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.
Return true
if n
is a happy number, and false
if not.
Example 1:
Input: n = 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
Example 2:
Input: n = 2 Output: false
Youtube Discussion
Solution
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.
class LC202 {
public:
int convert(int n){
int ans = 0;
while(n){
ans += pow(n%10, 2);
n/=10;
}
return ans;
}
bool isHappy(int n) {
bool map[1000];
memset(map, 0, sizeof(map));
n = convert(n);
while(!map[n]){
map[n] = true;
if(n == 1)
return true;
n = convert(n);
}
return false;
}
};
The code for this problem can be found in the following repository.