basics · intermediate · ~25 min
Build digits in reverse, then reverse.
Convert an integer to its decimal text form inside a caller-provided buffer — the inverse of atoi.
Implement int itoa_buf(int n, char *buf, size_t cap) that writes the decimal representation of n into buf as a NUL-terminated string. Return the number of characters written (not counting the NUL), or -1 if buf (capacity cap) is too small to hold the digits plus the terminator.
An int n, a destination buffer buf, and its capacity size_t cap (>= 1).
Returns the length of the written string (excluding the NUL) on success, or -1 if it would not fit.
itoa_buf(42, buf, 32) -> 2, buf == "42"
itoa_buf(-7, buf, 32) -> 2, buf == "-7"
itoa_buf(0, buf, 32) -> 1, buf == "0"
itoa_buf(INT_MIN, buf, 32) -> 11, buf == "-2147483648"
itoa_buf(1234, buf, 3) -> -1 (doesn't fit)
n == 0 writes "0" (length 1).INT_MIN: its magnitude is one larger than INT_MAX, so negate via unsigned.sprintf/snprintf — build the digits with plain arithmetic.Building a string from an integer is the inverse of atoi and crops up in every printf-without-printf scenario (kernel logging, embedded firmware, etc.).
An int n, a buffer buf, and its capacity size_t cap (>= 1).
Number of chars written (excluding NUL), or -1 if it doesn't fit.
No sprintf; plain arithmetic. Handle 0 and INT_MIN. NUL and '-' count toward cap.
#include <stddef.h>
int itoa_buf(int n, char *buf, size_t cap) { /* TODO */ return -1; }
-n overflows on INT_MIN; not handling zero (loop never runs); writing past the buffer.
n == 0 writes "0". n == INT_MIN — magnitude is one bigger than INT_MAX.
O(digit count).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.