Subj : Re: Reversing a number To : comp.programming From : pete Date : Tue Sep 13 2005 01:02 pm Rob Thorpe wrote: > > Willem wrote: > > Roger wrote: > > ) "Irrwahn Grausewitz" wrote in message > > ) news:shv7i1p3on0qpsr2rumeifst69o8tjtp32@4ax.com... > > )> But why treat the first iteration as a special case? > > )> Just replace the two lines above with: > > )> > > )> int n = 0; > > )> > > )>> while (i) > > )>> { > > )>> n *= 10; > > )>> n += i % 10; > > )>> i /= 10; > > )>> } > > )>> return n; > > )>>} > > ) > > ) Then reverse(10000) is (1). > > > > Of course it is; the function returns an integer, after all. > > I think the OP means a number in the mathematical sense of the word. > ie:- > > 1 -> 1 > 21 -> 12 > 5634 -> 4365 > > As Jerry Quinn pointed out > it's simplest to convert it to a string then > reverse it and convert it back again. #include #include int revdecimal(int number); void itoa_r(int n, char *s); int revdecimal(int number) { char string[sizeof number * CHAR_BIT / 3 + 1]; itoa_r(number, string); return atoi(string); } void itoa_r(int n, char *s) { int tenth, min_offset; char *p; min_offset = 0; if (0 > n) { if (-INT_MAX > n) { ++n; ++min_offset; } n = -n; *s++ = '-'; } p = s; tenth = n; do { tenth /= 10; *p++ = (char)(n - 10 * tenth + '0'); n = tenth; } while (tenth != 0); *s = (char)(*s + min_offset); *p = '\0'; } -- pete .