Recursive Digit Sum

  • + 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;
    }