The C Program: F_palindrometer/palin.c

  1 #include <stdio.h>
  2 #include <math.h>
  3 #include <string.h>
  4 
  5 // Make an 'n' digit palindrom with the first half equal to 'left'
  6 long makePalindrom (const int n, const long left) {
  7    long result = left;
  8    long h = (n%2==0)?left:left/10;
  9    int i;
 10    for (i=0; i<n/2; i++) {
 11       result *= 10;
 12       result += h%10;
 13       h /= 10;
 14    }
 15    return result;
 16 }
 17 
 18 
 19 int main (void) {
 20    char buffer[100];
 21    int i;
 22 
 23    while (1) {
 24       //      scanf ("%[^\n]\n", line);
 25       const char *line = fgets (buffer, 100, stdin);
 26       if (line==NULL) break;
 27       const int len = strlen (line)-1;
 28       if (len<=1) break;
 29       const long value = strtol (line, NULL, 10);
 30       buffer[(len-1)/2 + 1] = '\0';  // substring hack
 31       const long left_half = strtol (line, NULL, 10);
 32       long target = makePalindrom (len, left_half);
 33       if (target < value) {
 34          target = makePalindrom (len, left_half+1);
 35       }
 36       fprintf (stdout, "%d\n", target-value);
 37    }
 38    return 0;
 39 }
 40 
 41 /*
 42  * Local Variables:
 43  * compile-command: "gcc palin.c -lm -o palin"
 44  * End:
 45  */