The Java Program: F_palindrometer/Palindrometer.java

  1 /*
  2   SER 2010.  Problem F: Palindrometer
  3   Author: Ryan Stansifer 
  4 */
  5 
  6 import java.io.*;
  7 import java.util.Scanner;
  8 
  9 public final class Palindrometer {
 10 
 11    private static final Scanner STDIN =
 12       new Scanner (new BufferedInputStream (System.in));
 13 
 14    // Make an 'n' digit palindrom with the first half equal to 'left'
 15    public static int makePalindrom (final int n, final int left) {
 16       int result = left;
 17       int h = (n%2==0)?left:left/10;
 18       for (int i=0; i<n/2; i++) {
 19          result *= 10;
 20          result += h%10;
 21          h /= 10;
 22       }
 23       // System.err.printf ("n=%d, left=%d; target=%0"+n+"d%n", n, left, result);
 24       return result;
 25    }
 26 
 27    public static void main(String[] args) {
 28       for (;;) {
 29          final String st = STDIN.next();
 30          if (st.length()<=1) break;
 31          assert st.length()<=9;  // 2 to 9 digits long
 32          final int value = Int.parseInt (st);  // current value of spediometer
 33          final int length = st.length();
 34          // The first half of the string (possibly containing leading zeros)
 35          // is converted to a number.
 36          final int left_half = Int.parseInt (st.substring(0, (length-1)/2 + 1));
 37          int target = makePalindrom (length, left_half);
 38          if (target < value) {
 39              /* If the palindrom is smaller than current value of the
 40                 odometer then it is obviously not the next biggest
 41                 palindrom.  The next largest palindrom will increase
 42                 the least significant digit on the LHS by one.  The
 43                 will increase the bost significant digit on the LHS by
 44                 one and the resulting palindrom has to the biggeer
 45                 than the current value.
 46              */
 47             target = makePalindrom (length, left_half+1);
 48          }
 49          System.out.println (target-value);
 50       }
 51    }
 52 }