C# solution: HashSet and loop


  • 0
    B
    public class Solution 
    {
        public bool IsHappy(int n) 
        {
            if (n <= 0) return false;
            if (n == 1) return true;
    
            var numberSet = new HashSet<int>();
    
            while(n != 1)
            {
                var cur = 0;
                while(n != 0)
                {
                    var remainder = n % 10;
                    cur = remainder * remainder + cur;
                    n /= 10;
                }
    
                if (numberSet.Contains(cur)) return false;
    
                numberSet.Add(cur);
    
                n = cur;
            }
    
            return true;
        }
    }
    

Log in to reply
 

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