tags:

views:

357

answers:

3
+12  A: 

In the do-while loop, it is pulling the numbers off from behind (the least significant digit first). So, if you had the number -123456789, it processes the 9, then the 8, then the 7, etc.

So, when it hits the null-terminator (3rd to last line), you would have "987654321-", which is then reversed.

Erich
+2  A: 

n % 10 gives 0 for n = 10, so after the loop, the string s contains 01.

The call to reverse() fixes this.

Aaron Digulla
yh but what i want to know how its pulling numbers from behind ? by modulus operator ?
also if it does why since it just get the remainder i did the math the remainder is always after the . is that last number in the number but i don't know why dunno i m somewhat confused
nvm got it lol was stupid :P
A: 

The algorithm determines the digits from least to most significant order. Because the total number of digits that will be generated is not known in advance, the correct position cannot be determined as they are generated - the least significant digit will be at the end, but the 'end' is not known. So they are buffered in the order they are calculated (reverse) and then the whole string is reversed to correct the ordering.

One way of avoiding this is to determine the length in advance:

decimal_digits = (int)log10( n ) + 1 ;

but on devices without an FPU (and some with very simple FPUs) that is likely to be a heavier task than string reversal.

Clifford