| 13 | #define TO_DIGIT(n) ((n) + '0') |
| 14 | |
| 15 | void itoa(int num, char *str) { |
| 16 | int i = 0; |
| 17 | int isNegative = 0; |
| 18 | |
| 19 | if (num == 0) { |
| 20 | str[i++] = '0'; |
| 21 | str[i] = '\0'; |
| 22 | return; |
| 23 | } |
| 24 | |
| 25 | if (num < 0) { |
| 26 | isNegative = 1; |
| 27 | num = -num; |
| 28 | } |
| 29 | |
| 30 | while (num != 0) { |
| 31 | int rem = num % 10; |
| 32 | str[i++] = TO_DIGIT(rem); // Use macro |
| 33 | num = num / 10; |
| 34 | } |
| 35 | |
| 36 | if (isNegative) { |
| 37 | str[i++] = '-'; |
| 38 | } |
| 39 | |
| 40 | // Reverse the string (could be optimized) |
| 41 | for (int start = 0, end = i - 1; start < end; start++, end--) { |
| 42 | char temp = str[start]; |
| 43 | str[start] = str[end]; |
| 44 | str[end] = temp; |
| 45 | } |
| 46 | |
| 47 | str[i] = '\0'; |
| 48 | } |
| 49 | |
| 50 | // This function is almost identical to itoa. |
| 51 | // Consider refactoring to avoid code duplication |