In an interview I was asked to write a function that would take an input word and return true if the word is a palindrome. At first I used an approach using StringBuilder but the interviewer said that wasn't allowed and to use a for loop instead. I scored 7/9 so I'm guessing it's possible to improve this:
public static boolean isPalinedrome(String word) {
for(int i = 0; i < word.length(); i++) {
if(word.charAt(i) != word.charAt(word.length() - 1 - i)) {
return false;
}
}
return true;
}
I added the following to the main() section to test
String input = "racecar";
if(isPalinedrome(input)) {
System.out.println(input + " is a palinedrome");
} else {
System.out.println(input + " is not a palinedrome");
}
The way I test it seems to be ugly. Is there a standard way to test a new function? I guess if you're in an advanced enough environment you would have test cases for JUnit to run against it, but anything simpler that could be done in an interview with a cloud IDE?
"racecar"is a palindrome : you know it is. You should check thatisPalindrome("racecar")returnstrue. If not, raise an exception or display a big fat error message. \$\endgroup\$isPalinedrome()? \$\endgroup\$