Recursive Digit Sum

Sort by

recency

|

202 Discussions

|

  • + 0 comments
    Easy JavaScript Solution
    function superDigit(n, k) {
        if(n.length === 1){
            return n
        }
        let p = 0
        for(const num of n){
            const z = k*Number(num)
            p+=z
        }
       return superDigit(p.toString(), 1)
    }
    
  • + 0 comments

    c++ solution

    because the input is large, we gotta avoid creating the initial string by concatenating string n k times. Instead we calculate the sum of initial n and then multiply it by k to get sum of digits of concatenated k times string n. From then on, we simulate the process in the description - get the sum of string until its length is one.

     #define ll long long
    
    int superDigit(string n, int k) {
        string tmp = n;
        
        int len = tmp.size();
        int res = 0;
        
        while (len > 1) {
            ll sum = 0ll; 
            
            for (int i = 0; i < len; i++) {
                sum += int(tmp[i]-'0');
            }
            sum *= k;
            k=1;
            
            res = sum;
            
            string next = "";
            while (sum) {
                next += char((sum%10) + '0');
                sum /= 10;
            }
            tmp = string(next.rbegin(), next.rend());
            
            len = next.size();
        }
        return res;
    }
    
  • + 1 comment

    Python solution

    Explaining the code:

    "@nemat-al/recursive-digit-sum-hackerrank-python-db446d084a89">https://medium.com/@nemat-al/recursive-digit-sum-hackerrank-python-db446d084a89"

    def superDigit(n, k):
       # Base case: If n is already a single-digit number, return it as the super digit
       if len(n) == 1:
          return int(n)
       # Calculate the sum of the digits of n multiplied by k
       added = sum(int(i) for i in n) * k
       # Recursive call: with the sum converted to string and k set to 1
       # since repeated multiplication is only needed once  
       return superDigit(str(added), 1)
    
  • + 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);
    
        }
    
  • + 0 comments
    def superDigit(n, k):
        return (sum(map(int, list(n))) * k) % 9 or 9