Ad

When you need to vist each value of any value like arrays, list, stack or queue, you could use it because is more understandable (this is better way but in certain cases)

Code
Diff
  • public class Program {
      public static int loop(int repeat){
        //Trivial case 
        if(repeat == 1)
          return 0;
        //The trick is this line of code
        return loop(repeat-1)+1;
      }
    }
    • public class Program {
    • public static int loop(int repeat){
    • int result = 0;
    • for(String s = ""; s.length() < repeat; s += " ") {
    • result = s.length();
    • }
    • return Integer.parseInt(new Integer(result).toString().trim());
    • //Trivial case
    • if(repeat == 1)
    • return 0;
    • //The trick is this line of code
    • return loop(repeat-1)+1;
    • }
    • }