Recursive Digit Sum

  • + 0 comments

    Java

     public static int superDigit(String n, int k) {
            long sum = 0;
            for (char digit : n.toCharArray()) {
                sum += Character.getNumericValue(digit);
            }
    
            sum *= k;
            return superDigitHelper(sum);
        }
    
        private static int superDigitHelper(long n) {
            if (n < 10) return (int) n;
    
            long nextSum = 0;
            while (n > 0) {
                nextSum += n % 10;
                n /= 10;
            }
    
            return superDigitHelper(nextSum);
        }