Subj : Re: Reversing a number To : comp.programming From : Roger Willcocks Date : Sun Sep 11 2005 11:22 pm "Irrwahn Grausewitz" wrote in message news:shv7i1p3on0qpsr2rumeifst69o8tjtp32@4ax.com... > zeroxia@gmail.com wrote: >>Is this implementation not compiler-specific? >>(For example, the case of which i is negative. > > That's not a problem, if you don't mind that the result > will be negative, too. > >>int reverse(int i) >>{ >> int n = (i % 10); >> i /= 10; > > 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). Consider the normal recursive method of printing a number: printnumber(int number) { if (number >= 10) /* any leading digits? */ printnumber(number / 10); /* print them first */ print(number % 10); /* print the trailing digit */ } and think what happens if you print the rightmost digit before printing the other digits: printnumber(int number) { print(number % 10); if (number >= 10) printnumber(number / 10); } -- Roger .