Recursive Digit Sum

  • + 0 comments

    I really wanted this to work with recursion so I did. After looking here at the comments it seems that multiplying by 'k' after doing the first sum is the best way to optimize away the memory issues. Did this in C++, could be improved upon but i'll settle with this. Also had issues with the way the question was worded, guess I either need to improve my reading comprehension or this needs to be better.

    int superDigit(string n, int k) {
        
        // Base case
        if (n.length() == 1 && k == 0) {
            return std::stoi(n);
        }
        
        // First run
        if (k != 0) {
            size_t sum = 0;        
            for (size_t i = 0; i < n.length(); ++i) {
                sum += n.at(i) - '0';
            }
            sum = sum * k;
            return superDigit(to_string(sum), 0);
            
        } else { // Recursion body
            size_t sum = 0;        
            for (size_t i = 0; i < n.length(); ++i) {
                sum += n.at(i) - '0';
            }
    
            return superDigit(std::to_string(sum), 0);   
        }
    }