Skip to main content

Command Palette

Search for a command to run...

(11) STL: Happy Number

Published
1 min readView as Markdown
(11) STL: Happy Number
M

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:

  • Daily Data Structure and Algorithm based questions
  • Getting knowledge of various development-related tools, concepts, and practices

    Twitter , GitHub , LinkedIn and Hashnode

More from this blog

Untitled Publication

36 posts