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.
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.
intsuperDigit(stringn,intk){// Base caseif(n.length()==1&&k==0){returnstd::stoi(n);}// First runif(k!=0){size_tsum=0;for(size_ti=0;i<n.length();++i){sum+=n.at(i)-'0';}sum=sum*k;returnsuperDigit(to_string(sum),0);}else{// Recursion bodysize_tsum=0;for(size_ti=0;i<n.length();++i){sum+=n.at(i)-'0';}returnsuperDigit(std::to_string(sum),0);}}
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 →
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.