Recursive Digit Sum

Sort by

recency

|

56 Discussions

|

  • + 0 comments

    C#:

    public static int superDigit(string n, int k)
        {
            do
            {
                long sum = 0;
                foreach(char c in n)
                {
                    sum += int.Parse(c.ToString());
                }
                sum *= k;
                k=1;
                n = sum.ToString();
            }while(n.Count()!=1);
            
            return int.Parse(n);
        }
    
  • + 0 comments

    TypeScript

    function superDigit(n: string, k: number): number {
      let sum = 0;
    
      for (let char of n) {
        sum += Number(char);
      }
    
      sum *= k;
    
      if (sum <= 9) return sum;
    
      return superDigit(String(sum), 1);
    }
    
  • + 0 comments

    php

    function superDigit($n, $k) {
        $x = array_sum(str_split($n)) * $k;
    
        while ($x >= 10) {
            $x = array_sum(str_split($x));
        }
    
        return $x;
    }
    
  • + 0 comments

    Java

     public static int superDigit(String n, int k) {
            long sum = 0;
            for (char digit : n.toCharArray()) {
                sum += Character.getNumericValue(digit);
            }
    
            sum *= k;
            return superDigitHelper(sum);
        }
    
        private static int superDigitHelper(long n) {
            if (n < 10) return (int) n;
    
            long nextSum = 0;
            while (n > 0) {
                nextSum += n % 10;
                n /= 10;
            }
    
            return superDigitHelper(nextSum);
        }
    
  • + 2 comments

    Python3

    def superDigit(n, k):
        # Write your code here
        res = sum(int(i) for i in str(n)) * k
        while res > 10:
            res = sum(int(i) for i in str(res))
        return res