/* * revdec.c - Reverse decimal numbers. * Computes the reverse of any valid input integer in place. * * Naveed Hasan * 2002.12.27 * v1.1 */ /* Returns the integral portion of the logarithm base 10 of the input number. */ int log_10( int num ){ int result = -1; while( num > 0 ){ num /= 10; result++; } return result; } /* Returns the integral value of 10 raised to the power of the input number. */ int pow_10( int num ){ int result = 1; while( num > 0 ){ num--; result *= 10; } return result; } /* Returns the reverse of the input integer */ int rev_10( int num ){ int sign, width, lopos, hipos, lonum, hinum, diff, lodif, hidif; sign = num >= 0 ? 1 : -1; /* What is the sign of the number? */ num *= sign; /* Will be reversing the absolute value... */ width = log_10(num) + 1; /* What is the width of the number in digits? */ /* Swap the low & high halves of the decimal number. */ for( lopos = 1; lopos < width/2 + 1; lopos++ ){ hipos = width - lopos + 1; lonum = num % pow_10(lopos) / pow_10(lopos - 1); /* Digit in low & */ hinum = num % pow_10(hipos) / pow_10(hipos - 1); /* high position. */ diff = lonum >= hinum ? lonum - hinum : hinum - lonum; /* Difference. */ lodif = lonum >= hinum ? -diff : diff; hidif = lonum >= hinum ? diff : -diff; /* Actual swaps: simply addition of the appropriate values. */ num += (lodif * pow_10(lopos - 1) + hidif * pow_10(hipos - 1)); } num *= sign; /* Put the sign back on the reversed number! */ return num; } /* Main function. Rejects invalid input, which is defined as input which when * reversed may underflow or overflow an integer. */ int main( int argc, char** argv ){ int N = -1000000000; if( argc == 2 ) N = atoi(argv[1]); if( N < -999999999 || N > 999999999 ){ printf("Usage: %s number (%d, %d)\n", argv[0], -999999999, 999999999); return -1; } printf("%d\n", N); printf("%d\n", rev_10(N)); return 0; }