-
-
Notifications
You must be signed in to change notification settings - Fork 312
Expand file tree
/
Copy pathRecursiveDigitSum.java
More file actions
69 lines (54 loc) · 1.74 KB
/
RecursiveDigitSum.java
File metadata and controls
69 lines (54 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.hackerrank.algorithms.recursion;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/**
* Recursive Digit Sum Problem.
*
* @link https://www.hackerrank.com/challenges/recursive-digit-sum/problem
* @author rpatra16
* @since 06/11/2018
*/
public class RecursiveDigitSum {
/**
* Finds the recursive digit sum of n.
*
* @param n number
* @param k the number would be repeated k times
* @return recursive sum of the digits
*/
private static int superDigit(String n, int k) {
if(n == null) throw new Exception("by input exception [" + n + "]");
if (n.length() == 1 && k == 0) {
try {
return Integer.parseInt(n);
}catch (Exception e) {
throw new Exception("by input exception [" + n + "]");
}
}
Long sum = 0L;
char[] num = n.toCharArray();
for (int i = 0; i < num.length; i++) {
try {
sum += Long.parseLong(String.valueOf(num[i]));
} catch(Exception ex) {
throw new Exception("by input exception [" + n + "]");
}
}
if (k != 0) sum *= k;
return superDigit(sum.toString(), 0);
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] nk = scanner.nextLine().split(" ");
String n = nk[0];
int k = Integer.parseInt(nk[1]);
int result = superDigit(n, k);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}