// CSE 143, winter 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) public class Recursion { public static void main(String[] args) { System.out.println(pow(2, 3)); // 8 System.out.println(pow(5, 12)); // 25 System.out.println(pow(153, 3)); // 3 581 577 // System.out.println(pow(6, -1)); // crashes writeBinary(2); // 10 System.out.println(); writeBinary(12); // 1100 System.out.println(); writeBinary(-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 } // Returns the base raised to the exponent // Pre: exponent >= 0 // Throws IllegalArgumentException for negative exponents public static int pow(int base, int exponent) { if (exponent < 0) { throw new IllegalArgumentException("Exponent negative!"); } else if (exponent == 0) { return 1; } else if (exponent % 2 == 0) { // reduces number of calls return pow(base * base, exponent / 2); } else { return base * pow(base, exponent - 1); /* * If you can't see the pattern, write code for several of the cases * if (exponent == 1) { * return base; * } else if (exponent == 2) { * return base * base; // base * pow(base, 1) * } else if (exponent == 3) { * return base * base * base; // base * pow(base, 2) * } */ } } // Accepts an integer in base-10 as its parameter. // Prints that number's base-2 representation. public static void writeBinary(int n) { if (n < 0) { System.out.print("-"); writeBinary(-n); } else if (n < 2) { System.out.print(n); } else { writeBinary(n / 2); // print rest of digits System.out.print(n % 2); // print right-most digit } } // Returns true if the given string reads the same // forwards as backwards // This is so ninja!! public static boolean isPalindromeNinja(String word) { return word.length() < 2 || (word.charAt(0) == word.charAt(word.length() - 1) && isPalindrome(word.substring(1, word.length() - 1))); } // Less ninja, maybe easier to read. public static boolean isPalindrome(String s) { // empty string or single char are palindromes if (s.length() < 2) { return true; // base case } else { char first = s.charAt(0); char last = s.charAt(s.length() - 1); if (first != last) { return false; } // recursive case String middle = s.substring(1, s.length() - 1); return isPalindrome(middle); } } }