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.
My solution in Java language. After solved this problem, i believe there is no need to use recursion.
publicstaticintsuperDigit(Stringn,intk){// Write your code here/* Realizes that the super_digit of x is the sum of digits of x moduled by 9. Then realizes that value is equal to remain of x when divided by 9. However, the string is too long :( Sum of digits of that string is under 9*100000(according to the constraints) Edge case: super_digit(x) = 0 <=> x = 0 Steps: 1. Calculating the sum of digits. 2. Multipling the result with k, then calculating the result % 9 3. Check if the result is 0 and the sum is not 0 -> then return 9 Else return that result. Time complexity: O(L) with L is the length of the string Space complexity: O(1) This approach is still able to be better */intsum=0;//SUMfor(inti=0;i<n.length();i++){sum+=n.charAt(i)-'0';}intresult=sum;result%=9;//Just to ensure no error with long string and big kresult*=k;//K timesresult%=9;//The remain after divide by 9return(result==0&&sum!=0)?9:result;}
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 →
My solution in Java language. After solved this problem, i believe there is no need to use recursion.