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.
because the input is large, we gotta avoid creating the initial string by concatenating string n k times. Instead we calculate the sum of initial n and then multiply it by k to get sum of digits of concatenated k times string n.
From then on, we simulate the process in the description - get the sum of string until its length is one.
#define ll long longintsuperDigit(stringn,intk){stringtmp=n;intlen=tmp.size();intres=0;while(len>1){llsum=0ll;for(inti=0;i<len;i++){sum+=int(tmp[i]-'0');}sum*=k;k=1;res=sum;stringnext="";while(sum){next+=char((sum%10)+'0');sum/=10;}tmp=string(next.rbegin(),next.rend());len=next.size();}returnres;}
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
because the input is large, we gotta avoid creating the initial string by concatenating string n k times. Instead we calculate the sum of initial n and then multiply it by k to get sum of digits of concatenated k times string n. From then on, we simulate the process in the description - get the sum of string until its length is one.