public class Recursion { public static void main(String[] args) { System.out.println(pow(2, 6)); printBinary(6); System.out.println(isPalindrome("madam")); // true System.out.println(isPalindrome("palindrome")); // false System.out.println(isPalindrome("racecar")); // true System.out.println(isPalindrome("step on no pets")); // true System.out.println(isPalindrome("able was I ere I saw elba")); // true System.out.println(isPalindrome("Java")); // false System.out.println(isPalindrome("rotater")); // false System.out.println(isPalindrome("byebye")); // false System.out.println(isPalindrome("notion")); // false } // Returns the result of raising the base to the specified exponent. // pre: exp >= 0 public static int pow(int base, int exp) { if (exp == 0) { return 1; } else if (exp % 2 == 0) { // 2^16 --> (2^2)^8 // base^exp -> (base^2)^exp/2 return pow(base * base, exp / 2); } else { // 2^0 = 1 // 2^1 = 1 * 2 // 2^2 = 1 * 2 * 2 // 2^3 = 1 * 2 * 2 * 2 return base * pow(base, exp - 1); } } // Prints the given decimal value in binary // pre: decimal >= 0 public static void printBinary(int decimal) { if (decimal < 2) { System.out.print(decimal); } else { printBinary(decimal / 2); printBinary(decimal % 2); // last digit by doing mod 2 and CONVERT IT TO BINARY // get the rest by doing / 2 and CONVERT IT TO BINARY } } // Returns true if the given String reads the same // forwards as backwards and false otherwise. public static boolean isPalindrome(String word) { if (word.length() < 2) { return true; } else { // a word is a palindrome if the first and last characters match // and the rest is a palindrome // char first = word.charAt(0); // char last = word.charAt(word.length() - 1); // // if (first != last) { // return false; // } // // the first and last match so see if the rest is a palindrome // return isPalindrome(word.substring(1, word.length() - 1)); // "zen" version return word.charAt(0) == word.charAt(word.length() - 1) && isPalindrome(word.substring(1, word.length() - 1)); } } }