c# solution


  • 1
    K

    idea is to break out of loop when you encounter a value that was previously processed.

    public class Solution {
        public bool IsHappy(int n) {
            HashSet<int> seenValues = new HashSet<int>();
            while (n != 1)
            {
                int sum = 0; 
                do
                {
                    int remainder = n % 10;
                    sum = sum +  (remainder * remainder);
                    n = n /10;
                } while( n != 0);
                
                if(seenValues.Contains(sum))
                {
                    // This indicates loop
                    return false;
                }
                else
                {
                    seenValues.Add(sum);
                }
                n = sum;
            }
            
            return true;
        }
    
    }
    

Log in to reply
 

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