// CSE 143, Summer 2012 // This program includes code for several recursive methods. // For each of these methods, we identified: // - the easiest version of the problem to solve (base case) // - a small piece of the problem we could solve that gets us // closer to the base case (recursive case) import java.util.*; import java.io.*; public class Recursion { public static void main(String[] args) throws FileNotFoundException { /* System.out.println(pow(2, 3)); // 8 System.out.println(pow(5, 2)); // 25 System.out.println(pow(153, 3)); // 3 581 577 System.out.println(pow(6, 1)); // 6 printBinary(2); // 10 System.out.println(); printBinary(12); // 1100 System.out.println(); printBinary(-500); // 111110100 System.out.println(); System.out.println(isPalindrome("madam")); // true System.out.println(isPalindrome("step on no pets")); // true System.out.println(isPalindrome("Java")); // false */ reverseLines(new Scanner (new File("cookie.txt"))); } // Returns the base raised to the exponent // Pre: exponent >= 0 public static int pow(int base, int exp) { if (exp == 0) { return 1; } else if (exp % 2 == 0) { // call pow passing our new values return pow (base * base, exp / 2); } else { return base * pow (base, exp - 1); } } // Accepts an integer in base-10 as its parameter. // Prints that number's base-2 representation. public static void printBinary(int n) { if (n < 0) { System.out.print("-"); printBinary(-n); } else if (n < 2) { System.out.print(n); } else { // 101010 printBinary(n / 2); // 10101 printBinary(n % 2); // 0 } } // returns true if the string is the same backwards // and forwards. public static boolean isPalindrome(String s) { if (s.length() < 2) { return true; } else { char first = s.charAt(0); char last = s.charAt(s.length() - 1); if (first != last) { return false; } String middle = s.substring(1, s.length() - 1); return isPalindrome(middle); } } public static boolean isPalindromeNinja(String s) { return true; } // reverses the lines in the input public static void reverseLines(Scanner input) { if (input.hasNextLine()) { String line = input.nextLine(); reverseLines(input); System.out.println(line); } } }