pointers-memory · intermediate · ~18 min

Implement atoi

String → integer conversion, the classic interview problem.

Challenge

Write your own atoi: turn the leading number in a string into an int, like the classic interview question.

Task

Implement int my_atoi(const char *s) that parses s as: optional leading spaces, an optional + or - sign, then decimal digits. Parsing stops at the first non-digit. No main — the grader calls it.

Input

A NUL-terminated string s. It may have leading spaces, a sign, digits, and trailing junk.

Output

The parsed integer as an int. If there are no digits, return 0. Trailing non-digit characters are ignored.

Example

my_atoi("42")        ->   42
my_atoi("-7")        ->   -7
my_atoi("   123")    ->   123
my_atoi("99abc")     ->   99
my_atoi("")          ->   0
my_atoi("-")         ->   0

Edge cases

  • Empty string or a lone sign returns 0.
  • Stop at the first non-digit after the optional sign.

Rules

  • Do not handle overflow (assume the value fits in int).

Why this matters

Transfer exercise: apply the lesson to a complete function contract.

Input format

A NUL-terminated string s. It may have leading spaces, a sign, digits, and trailing junk.

Output format

The parsed integer as an int. If there are no digits, return 0. Trailing non-digit characters are ignored.

Constraints

Non-NULL terminated string; leading spaces/tabs, optional sign, then digits. Mathematical value fits int. Return zero if no digits; do not allocate or mutate.

Starter code

int my_atoi(const char *s) {
    /* TODO */
    return 0;
}

Common mistakes

Overflowing an int while building the positive magnitude of INT_MIN.

Edge cases to handle

Empty string; lone sign; trailing junk; INT_MIN/INT_MAX; tabs before sign.

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