package cse1030; import java.util.ArrayList; import java.util.List; public class Practice2 { public static int sum(List t) { if (t.isEmpty()) { return 0; } return t.get(0) + Practice2.sum(t.subList(1, t.size())); } public static String reverse(String s) { if (s.isEmpty()) { return ""; } /* * * Both of the following work: * * (a) last character + reverse(substring from first to second last character) return s.charAt(s.length() - 1) + Practice2.reverse(s.substring(0, s.length() - 1)); * (b) reverse(substring from second character to end) + first character return Practice2.reverse(s.substring(1, s.length())) + s.charAt(0); */ return s.charAt(s.length() - 1) + Practice2.reverse(s.substring(0, s.length() - 1)); } public static void main(String[] args) { List t = new ArrayList(); System.out.println(t + " : " + Practice2.sum(t)); t.add(10); System.out.println(t + " : " + Practice2.sum(t)); t.add(5); System.out.println(t + " : " + Practice2.sum(t)); t.add(-100); System.out.println(t + " : " + Practice2.sum(t)); String s = ""; System.out.println(s + " : " + Practice2.reverse(s)); s = "a"; System.out.println(s + " : " + Practice2.reverse(s)); s = "ab"; System.out.println(s + " : " + Practice2.reverse(s)); s = "abc"; System.out.println(s + " : " + Practice2.reverse(s)); } }