fork download
  1. class Main{
  2. String g(int n, int depth){ // Recursive method with 2 int parameters & String return-type
  3. int remainder = n % depth; // The current recursive remainder
  4. if(depth < n){ // If we aren't done with the number yet:
  5. int nextDepth = depth * 10; // Go to the next depth (of the power of 10)
  6. int nextN = n - remainder; // Remove the remainder from the input `n`
  7. // Do a recursive call with these next `n` and `depth`
  8. String resultRecursiveCall = g(nextN, nextDepth);
  9. if(remainder != 0){ // If the remainder was not 0:
  10. // Append a " + " and this remainder to the result
  11. resultRecursiveCall += " + " + remainder;
  12. }
  13. return resultRecursiveCall; // And return the result
  14. } else{ // Else:
  15. return Integer.toString(n); // Simply return input `n` as result
  16. }
  17. }
  18.  
  19. String f(int n){ // Second method so we can accept just integer `n`
  20. return g(n, 1); // Which will call the recursive call with parameters `n` and 1
  21. }
  22.  
  23. public static void main(String[] a){
  24. Main m = new Main();
  25. m.test(9);
  26. m.test(10);
  27. m.test(12);
  28. m.test(101);
  29. m.test(123);
  30. m.test(1024);
  31. m.test(70304);
  32. }
  33.  
  34. void test(int input){
  35. System.out.println(f(input));
  36. }
  37. }
Success #stdin #stdout 0.08s 2249728KB
stdin
Standard input is empty
stdout
9
10
10 + 2
100 + 1
100 + 20 + 3
1000 + 20 + 4
70000 + 300 + 4