| 
 | 1 | +package com.hackerrank.algorithms.recursion;  | 
 | 2 | + | 
 | 3 | +import java.io.BufferedWriter;  | 
 | 4 | +import java.io.FileWriter;  | 
 | 5 | +import java.io.IOException;  | 
 | 6 | +import java.util.Scanner;  | 
 | 7 | + | 
 | 8 | +/**  | 
 | 9 | + * Recursive Digit Sum Problem.  | 
 | 10 | + *  | 
 | 11 | + * @link https://www.hackerrank.com/challenges/recursive-digit-sum/problem  | 
 | 12 | + * @author rpatra16  | 
 | 13 | + * @since 06/11/2018  | 
 | 14 | + */  | 
 | 15 | +public class RecursiveDigitSum {  | 
 | 16 | + | 
 | 17 | +    /**  | 
 | 18 | +     * Finds the recursive digit sum of n.  | 
 | 19 | +     *  | 
 | 20 | +     * @param n number  | 
 | 21 | +     * @param k the number would be repeated k times  | 
 | 22 | +     * @return recursive sum of the digits  | 
 | 23 | +     */  | 
 | 24 | +    private static int superDigit(String n, int k) {  | 
 | 25 | +        if (n.length() == 1 && k == 0) {  | 
 | 26 | +            return Integer.parseInt(n);  | 
 | 27 | +        }  | 
 | 28 | + | 
 | 29 | +        Long sum = 0L;  | 
 | 30 | +        char[] num = n.toCharArray();  | 
 | 31 | +        for (int i = 0; i < num.length; i++) {  | 
 | 32 | +            sum += Long.parseLong(String.valueOf(num[i]));  | 
 | 33 | +        }  | 
 | 34 | + | 
 | 35 | +        if (k != 0) sum *= k;  | 
 | 36 | + | 
 | 37 | +        return superDigit(sum.toString(), 0);  | 
 | 38 | +    }  | 
 | 39 | + | 
 | 40 | +    private static final Scanner scanner = new Scanner(System.in);  | 
 | 41 | + | 
 | 42 | +    public static void main(String[] args) throws IOException {  | 
 | 43 | +        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));  | 
 | 44 | + | 
 | 45 | +        String[] nk = scanner.nextLine().split(" ");  | 
 | 46 | + | 
 | 47 | +        String n = nk[0];  | 
 | 48 | + | 
 | 49 | +        int k = Integer.parseInt(nk[1]);  | 
 | 50 | + | 
 | 51 | +        int result = superDigit(n, k);  | 
 | 52 | + | 
 | 53 | +        bufferedWriter.write(String.valueOf(result));  | 
 | 54 | +        bufferedWriter.newLine();  | 
 | 55 | + | 
 | 56 | +        bufferedWriter.close();  | 
 | 57 | + | 
 | 58 | +        scanner.close();  | 
 | 59 | +    }  | 
 | 60 | +}  | 
0 commit comments