202. Happy Number (LeetCode) Solution - TechTalkBot

 



202. Happy Number (LeetCode)

Solution (TechTalkBot)

Question :

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, and 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 numbers.
Return True if n is a happy number, and False if not.

Example: 

Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Solution :

Intuition behind this problem is to keep replacing the numbers by their sum of square of their digits. Ex- for 45 can be replaced by (4^2 + 5^2 = 49). Now this 49 can be replaced by (4^2 + 9^2 = 97) and so on. till the number becomes 1.
But for some numbers like 4, it never comes down to 1, but it enters an infinite loop if we repeat the above process.

Here is a solution video for the whole intuition and explanation for this question.

Code :

Here is the complete code for different approaches :

//USING SET
class Solution {
public:
bool isHappy(int n) {
set<int> myset;
int val;
int index;
while(1)
{
val = 0;
while(n)
{
index = n%10;
val += index*index;
n /=10;
}
if(val==1)
return true;
else if(myset.find(val)!=myset.end())
return false;
myset.insert(val);
n = val;
}
return false;
};
//USING TRIAL & ERROR
class Solution {
public:
bool isHappy(int n) {
int counter = 6;
int val;
int index;
while(counter)
{
val = 0;
while(n)
{
index = n%10;
val += index*index;
n /=10;
}
if(val==1)
return true;
n = val;
counter -= 1;
}
return false;
}
};

Feel free to ask questions and share solutions that you used to solve the problem.

Post a Comment

Previous Post Next Post