Interview Question

Interview San Francisco, CA

Implement 2 functions, is_palindrome() and max_int(). The

  first function returns True if the given string is a palindrome, and False if not. The second function returns the largest integer that is (1) the product of two 3 digit integers, and (2) is a palindrome.
Tags:
coding
Answer

Interview Answer

1 Answer

0

/** * method checks if given word is a palindrome * @param word * @return true if word is palindrome, false otherwise */ public boolean is_palindrome (String word) { if (word == null) return false; word = word.toLowerCase(); int i = 0; int j = word.length() - 1; while (i < j) { if (word.charAt(i) != word.charAt(j)) return false; i++; j--; } return true; } /** * method finds largest integer that is the product of two integers in the range [start, end], * and a palindrome * @param start * @param end * @return max palindrome found or -1 if there is no such number */ public int max_palindrome(int start, int end) { int maxpal = -1; int num = 0; for (int i = start; i <= end; i++) { for (int j = i; j <= end; j++) { int prod = i * j; if (prod > maxpal) { if (is_palindrome("" + prod)) { num++; System.out.println(num + ":\t " + i + " * " + j + " = " + prod); maxpal = prod; } } } } return maxpal; } max_palindrome called with parameters start = 101 and end = 999 will return 906609 as the largest such integer (= 913 * 993).

Christine on Jul 31, 2013

Add Answers or Comments

To comment on this, Sign In or Sign Up.