0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

HackerRank : Recursive Digit Sum

Posted at
#include <bits/stdc++.h>

using namespace std;

vector<string> split_string(string);

// Complete the superDigit function below.

int superDigit(string n, int k) {
    if(k>0){
        long long res=0;
        for(int i=0;i<n.size();i++)res+=n[i]-'0';
        n=to_string(res*k);
        return superDigit(n, 0);
    }else{
        long long res=0;
        for(int i=0;i<n.size();i++){
            res+=(n[i]-'0')%9;
            res%=9;
        }
        return res==0?9:res;
    // cout << "idx:" << idx << "n:" << n.c_str() << boolalpha << isFirst << "\n";
    /* if(n.length()==1)return stoi(n);
    int res=0;
    string temp=n;
    for(int i=1;i<k;i++)n+=temp;
    for(size_t i=0;i<n.length();i++)res+=n[i]-'0';
    n=to_string(res);
    return superDigit(n,0); */
    }
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    string nk_temp;
    getline(cin, nk_temp);

    vector<string> nk = split_string(nk_temp);

    string n = nk[0];

    int k = stoi(nk[1]);
    
    int result = superDigit(n, k);

    fout << result << "\n";

    fout.close();

    return 0;
}

vector<string> split_string(string input_string) {
    string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
        return x == y and x == ' ';
    });

    input_string.erase(new_end, input_string.end());

    while (input_string[input_string.length() - 1] == ' ') {
        input_string.pop_back();
    }

    vector<string> splits;
    char delimiter = ' ';

    size_t i = 0;
    size_t pos = input_string.find(delimiter);

    while (pos != string::npos) {
        splits.push_back(input_string.substr(i, pos - i));

        i = pos + 1;
        pos = input_string.find(delimiter, i);
    }

    splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));

    return splits;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?