Recursive Digit Sum

  • + 1 comment

    My solution in Java language. After solved this problem, i believe there is no need to use recursion.

    public static int superDigit(String n, int k) {
        // 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
            */
            
            int sum = 0; //SUM
            for(int i = 0; i < n.length(); i++){
                sum += n.charAt(i) - '0';
            }
            
            int result = sum;
            result %= 9; //Just to ensure no error with long string and big k
            result *= k; //K times
            result %= 9; //The remain after divide by 9
            
            return (result == 0 && sum != 0) ? 9 : result; 
        }