Recursive Digit Sum

  • + 0 comments

    For anyone struggling with the last test case and getting overflow: you might have to use a 64-bit integer to hold the super digit value, even if you choose to return a 32-bit integer at the end:

    int superDigit(string n, int k) {
        if(n.size() == 1 && k == 1) return stoi(n);
        long super_digit = 0;
        for(char c : n){
            int current = c - '0';
            super_digit += current;
        }
        super_digit *= k;
        return superDigit(to_string(super_digit), 1);
    }