I've seen variations of this assignment where you reverse a string to match it to the original to find out if it is a palindrome, but this version I made only iterates through half of the string comparing it in reverse and would terminate the loop as soon as it notices a difference between the mirrored char and the current one in the index loop. This causes fewer loops than a reversal of the string.
- There is a statement with a ternary operator and a modulus that could be perceived as hard to read.
Is there a better way than comparing chars? If you saw this in a code test as an answer, what would you assess this as? Is the more complex line with the ternary operator showing a more advanced knowledge of options or is it only hard to read?
Any other comments are welcome!
public boolean checkPalindrome(String word) {
boolean palindrome = true;
int wordLength = word.length() - 1;
// If the word is dividable by 2 return half else return half including the middle char
int halfWord = word.length() % 2 == 0? (word.length()/2) : ((int) word.length()/2) + 1 ;
for(int i = 0; i < halfWord; i++) {
char first = word.toLowerCase().charAt((wordLength - i));
char last = word.toLowerCase().charAt(i);
if(!(first == last)) {
palindrome = false;
break;
}
}
return palindrome;
}