My implementation uses a linked list:
import java.io.*;
import java.util.*;
public class NumericPalindrome {
public NumericPalindrome() {
while(input()); // loop, just calling input method
System.exit(0);
}
// one lot of input - take a line, read it char by char until encountering a
// newline
// return true if successfully read line and called isPalendromic,
// exit(1) otherwise
private boolean input() {
// java console input is gnarly!
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(isr);
char nextTok=' '; // character to read from inputstream into
Integer myInt; // Integer object - will throw exception for
// and make us exit(1) non numeric chars
LinkedList list = new LinkedList(); // Well, it isn't an array!
// rely on numberformat exception to meet the -1 exit clause
try {
// -1 is the end of a line
while ((nextTok = (char)input.read())!=-1) {
// skip newline chars
if(nextTok == '\n' || nextTok == '\r') break;
myInt =
new Integer( Integer.parseInt(nextTok+""));
// don't allow negative numbers
if (myInt.intValue()<0) break;
// append Integer to list
list.add(myInt);
}
System.out.println(isPalindromic(list));
return true;
}
catch (Exception ex) {
System.exit(1);
}
return false; // should never get here!
}
// read a linked list from outside inwards, i.e. compare elements starting with
// first and last, then second and penultimate and so on.
private boolean isPalindromic(LinkedList list) {
while (list.size() >= 2) {
if (! list.removeFirst().equals(list.removeLast()))
return false;
}
if (list.size()<2)
return true; // i.e. there are no more elements, or only
// one.
return false;
}
public static void main (String argv[]) {
new NumericPalindrome();
}
}
--
Don't Stand on your head - you'll get footprints in your hair
http://charlieharvey.org.uk
http://charlieharvey.com