Recursive Digit Sum

  • + 0 comments
    public static int superDigit(String n1, int k) {
        long digitSum = getDigitSum(n1) * k;
        return getSuperDigit(digitSum);
    }
    
    private static long getDigitSum(String n) {
        long sum = 0;
        for (int i = 0; i < n.length(); i++) {
            sum += n.charAt(i) - '0';
        }
        return sum;
    }
    
    private static int getSuperDigit(long n) {
        if (n < 10) {
            return (int) n;
        } else {
            return getSuperDigit(n % 10 + getSuperDigit(n / 10));
        }
    }
    

    we separate the calculation of the digit sum from the calculation of the super digit. The getDigitSum method calculates the sum of the digits of the input string n1. Then, we multiply the sum by k and pass it to the getSuperDigit method to obtain the final super digit.

    The getSuperDigit method uses recursion to repeatedly calculate the sum of the digits until a single-digit super digit is obtained. By using recursion, we avoid unnecessary loops and make the code more concise.