Recursive Digit Sum

  • + 0 comments

    C#

    public static int superDigit(string n, int k)
        {
            long digitSum(string str)
            {
                long sum = 0;
                foreach (char c in str)
                {
                    sum += c - '0';
                }
                return sum;
            }
    
            long initialSum = digitSum(n) * k;
    
            while (initialSum >= 10)
            {
                initialSum = digitSum(initialSum.ToString());
            }
    
            return Convert.ToInt32(initialSum);
    
        }