We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
int superDigit(string n, int k) {
//Base case. If n is a super digit and it doesn't need to be concatenated
if((n.size() == 1) && (k == 1))
{
return n[0] - '0';
}
//We intialize rVal as a long long so that it can handle the large test cases
long long rVal = 0;
//For each loop goes through each char in n
for(char c : n)
{
// Add the value of the char - the value of '0' to rVal
rVal += c - '0';
}
//Multiple rVal by k,This is the same as concatenating it
rVal *= k;
//Convert to a string
n = to_string(rVal);
//Recursively do this until the base case is reached
return superDigit(n, 1);
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Recursive Digit Sum
You are viewing a single comment's thread. Return to all comments →
C++ SOLUTION:
int superDigit(string n, int k) { //Base case. If n is a super digit and it doesn't need to be concatenated if((n.size() == 1) && (k == 1)) { return n[0] - '0'; } //We intialize rVal as a long long so that it can handle the large test cases long long rVal = 0;
}