/* Problem 4--Invertible Years This was a very straightforward problem. Just routinely count through the years until an invertible one is found. */ #include #include int main (int argc, char **argv); int Invert (int year); int main (int argc, char **argv) { FILE *in, *out; int cs, year, i; in = fopen ("prob4.in","r"); out = fopen ("prob4.out","w"); cs = 0; while (1) { /* Read in year */ fscanf (in,"%d",&year); if (year==0) break; /* Invert subsequent years one at a time. */ for (i=year+1;!Invert(i);i++); fprintf (out,"Case %d: The first invertible year after %d is %d.\n", ++cs,year,i); } fclose (in); fclose (out); return EXIT_SUCCESS; } /* Inverts returns whether the specified year is invertible. */ int Invert (int year) { int d, inv, y; inv = 0; y = year; while (y > 0) { /* Pull digits one at a time from right */ d = y%10; switch (d) { /* Build inverted number */ case 0: inv = 10*inv;break; case 1: inv = 10*inv+1;break; case 6: inv = 10*inv+9;break; case 8: inv = 10*inv+8;break; case 9: inv = 10*inv+6;break; default: return 0; /* bad digit */ } y /= 10; } return year == inv; /* Are they equal? */ }