pointers-memory · intermediate · ~15 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).

Input format

A NUL-terminated string s (optional spaces, optional +/- sign, digits, junk).

Output format

The parsed int; 0 when no digits are present.

Constraints

Stop at the first non-digit; do not handle overflow.

Starter code

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

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