basics · intermediate · ~25 min
Build digits in reverse, then reverse.
Implement int itoa_buf(int n, char *buf, size_t cap) that writes the decimal representation of n into buf (NUL-terminated). Returns the number of chars written (excluding NUL), or -1 if cap was too small. Handle negative and INT_MIN.
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.).
n is int. cap >= 1.
See API.
No sprintf. Plain arithmetic.
#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.