Subj : Re: Reversing a number To : comp.programming From : Gerry Quinn Date : Tue Sep 13 2005 05:12 pm In article <4326BFE2.2775@mindspring.com>, pfiland@mindspring.com says... > 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); Depends on the language. E.g. Blitz Basic 3D: Function GetReverse( x ) a$ = x For i = Len( a$ ) To 1 Step -1 b$ = b$ + Mid$( a$, i, 1 ) Next return b$ End Function (This language can automatically cast between integers and their decimal string representations.) - Gerry Quinn > 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'; > } > > .