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.
This problem can be solved mathematically.
The result is a "digital root."
Before beginning the usual calculations, it's necessary to prepare for them:
publicstaticintsuperDigit(Stringn,intk){longsum=0;for(inti=0;i<n.length();i++){//optimising first valuesum+=n.charAt(i)-'0';//'0' - because n.charAt(i) - returns ASCII code instead value itself}sum*=k;//Multiplication after a single calculationreturnMath.toIntExact(1+((sum-1)%9));}
If we don't need to calculate huge values like n=861568688536788, k=100000, we can use a simple calculation:
1+(Integer.parseInt(n.repeat(k))-1)%9;// String.repeat since Java 11
However, both options are not entirely suitable, since they do not solve the problem head-on, through a loop and recursion.
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 →
This problem can be solved mathematically. The result is a "digital root." Before beginning the usual calculations, it's necessary to prepare for them:
If we don't need to calculate huge values like n=861568688536788, k=100000, we can use a simple calculation:
However, both options are not entirely suitable, since they do not solve the problem head-on, through a loop and recursion.