(11) STL: Happy Number

I am Computer Science Graduate and Web Developer.
Question Link and Solution Link
Difficulty: Easy
Problem Statement: Given a number we need to find the sum of the square of digits of the number till the resultant is 1. If the resultant is 1 return true else false.
Approach: We will use a set to maintain unique elements. If at any point we get repeated elements we break out of the loop. Else we simply perform computation and check for the condition.
bool isHappy(int n)
{
set<int> st;
int s, sum;
while (st.find(n) == st.end())
{
if (n == 1) return true;
st.insert(n);
s = n, sum = 0;
while (s)
{
sum += pow(s % 10, 2);
s /= 10;
}
n = sum;
}
return false;
}
Subscribe to the newsletter so that you never miss any post or update just like this one.
You can follow me on Hashnode for:


