Write a
program to print number of dots in ascending sequence of integers beginning
from 1, each followed by dots as many as the preceding integer.
printDots(1)
= 1.
printDots(2)
= 1.2..
printDots(3)
= 1.2..3…
printDots(4) = 1.2..3…4….
printDots(4) = 1.2..3…4….
public class PrintDots { public static String getPrintDots(int n) { if (n < 1) throw new IllegalArgumentException("input should greater than 0"); return print(1, n); } private static String print(int k, int n) { if (k > n) return ""; return k + printDotKTimes(k) + print(++k, n); } private static String printDotKTimes(int k) { if (k == 0) return ""; return "." + printDotKTimes(--k); } }
Following is
the junit test case.
import static org.junit.Assert.assertEquals; import org.junit.Test; public class PrintDotsTest { @Test public void test1() { assertEquals(PrintDots.getPrintDots(1), "1."); assertEquals(PrintDots.getPrintDots(2), "1.2.."); assertEquals(PrintDots.getPrintDots(3), "1.2..3..."); assertEquals(PrintDots.getPrintDots(4), "1.2..3...4...."); assertEquals(PrintDots.getPrintDots(5), "1.2..3...4....5....."); } @Test(expected=IllegalArgumentException.class) public void test2() { PrintDots.getPrintDots(0); } }
No comments:
Post a Comment