Simple and efficient c# solution


  • 0
    T
    public bool IsHappy(int n)
            {
                HashSet<int> seen = new HashSet<int>();
                while (n != 1)
                {
                    if (seen.Contains(n))
                    {
                        return false;
                    }
    
                    seen.Add(n);
                    n = SumOfSquares(n);
                }
    
                return true;
            }
    
            int SumOfSquares(int n)
            {
                int sum = 0;
    
                while (n > 0)
                {
                    int digit = n % 10;
                    sum += (int)Math.Pow(digit, 2);
                    n = n / 10;
                }
    
                return sum;
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.