basics · intermediate · ~25 min

Convert int to string in a fixed buffer

Build digits in reverse, then reverse.

Challenge

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.

Why this matters

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.).

Input format

n is int. cap >= 1.

Output format

See API.

Constraints

No sprintf. Plain arithmetic.

Starter code

#include <stddef.h>
int itoa_buf(int n, char *buf, size_t cap) { /* TODO */ return -1; }

Common mistakes

-n overflows on INT_MIN; not handling zero (loop never runs); writing past the buffer.

Edge cases to handle

n == 0 writes "0". n == INT_MIN — magnitude is one bigger than INT_MAX.

Complexity

O(digit count).

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.