2.Happy Number

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.

class Solution
{
public:
    int sumSquares(int n)
    {
        int sum = 0;
        while (n > 0)
        {
            int x = n % 10;
            int sq = x * x;
            sum = sum + sq;
            n = n / 10;
        }
        return sum;
    }

    bool isHappy(int n)
    {
       int ans;
       unordered_set<int> s;
       bool res;
        while (true)
        {
            ans = sumSquares(n);
            cout<<ans<<" ";
            if (ans == 1)
            {
                res = true;
                break;
            }

            if (s.find(ans)!=s.end())
            {
                res = false;
                break;
            }

            s.insert(ans);
            n = ans;
        }
        
        return res;
    }
};

Last updated