Happy Number C# Solution 1 -- Recursion


  • 0
    M

    ** Happy Number C# Solution 1 -- Recursion **

    public class Solution {
        public bool IsHappy(int n) {
           int remainder;
                int quotient;
    
                List<int> digitArray = new List<int>();
                while (n > 9)
                {
                    quotient = System.Math.DivRem(n, 10, out remainder);
                    digitArray.Add(remainder);
                    n = quotient;
                }
                digitArray.Add(n);
    
                int result = 0;
                foreach (int i in digitArray)
                {
                    result = result + i * i;
                }
    
                if (result == 1)
                {
                    return true;
                }
                else if (result == 4  || result == 0)
                {
                    return false;
                }
                else
                {
                    return IsHappy(result);
                }
    
            
        }
    }
    
    

Log in to reply
 

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