Share my C# solution with hashset and Recursion


  • 0
    Y

    public class Solution {
    public bool IsHappy(int n) {

        var current=new HashSet<int>();
        
        return IsHappyWithHash(n, current);
    }
    
    //recreservely check
    public bool IsHappyWithHash(int n,HashSet<int> current) {
        
        var nextNumber=GetSquares(n);
        
        if(nextNumber==1)
            return true;
        
        if(current.Contains(nextNumber))
            return false;
        
        current.Add(nextNumber);
        
        return IsHappyWithHash(nextNumber,current);
    }
    
    //get squeares
    public int GetSquares(int n)
    {
        int result=0;
        
        while(n>0)
        {
            result += (n % 10)*(n % 10);
            n/=10;
        }
        
        return result;
    }
    

    }


Log in to reply
 

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