Create a triangle out of stars using only recursion

前端 未结 10 845
独厮守ぢ
独厮守ぢ 2020-12-06 06:52

I need to to write a method that is called like printTriangle(5);. We need to create an iterative method and a recursive method (without ANY iteration). The out

10条回答
  •  独厮守ぢ
    2020-12-06 07:26

    package playground.tests;
    
    import junit.framework.TestCase;
    
    public class PrintTriangleTest extends TestCase {
        public void testPrintTriangle() throws Exception {
            assertEquals("*\n**\n***\n****\n*****\n", printTriangleRecursive(5, 0, 0));
        }
    
        private String printTriangleRecursive(int count, int line, int character) {
            if (line == count)
                return "";
            if (character > line)
                return "\n" + printTriangleRecursive(count, line + 1, 0);
            return "*" + printTriangleRecursive(count, line, character + 1);
        }
    
    }
    

提交回复
热议问题