The exercise asks for a solution that is machine independent, but in "2.5 Arithmetic Operators" it says that the direction of truncation for / is machine-dependent for negative operands. Doesn't this mean that (for instance) if n = -86 then after n /= 10, n could be either -8 or -9 ? --FranklinHyde 20:18, 24 March 2008 (UTC)
Work entirely with negatives
It occurred to me that if the range of negative numbers was larger than positive, why not work entirely on the negative side?
- Change if((sign = n) < 0) to if((sign = n) > 0) to force n to be negative always
- Change s[i++] = n % 10 + '0'; to s[i++] = n % 10 * -1 + '0'; to force the remainder to calculate to a positive
- Change while((n /= 10) > 0); to while((n /= 10) < 0); since we're dividing out the negatives now
void _itoa(char n, char s[]) { int i, sign; if((sign = n) > 0) n = -n; i = 0; do { s[i++] = n % 10 * -1 + '0'; } while((n /= 10) < 0); if(sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); }