pointers-memory · intermediate · ~18 min
String → integer conversion, the classic interview problem.
Write your own atoi: turn the leading number in a string into an int, like the classic interview question.
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.
A NUL-terminated string s. It may have leading spaces, a sign, digits, and trailing junk.
The parsed integer as an int. If there are no digits, return 0. Trailing non-digit characters are ignored.
my_atoi("42") -> 42
my_atoi("-7") -> -7
my_atoi(" 123") -> 123
my_atoi("99abc") -> 99
my_atoi("") -> 0
my_atoi("-") -> 0
0.int).Transfer exercise: apply the lesson to a complete function contract.
A NUL-terminated string s. It may have leading spaces, a sign, digits, and trailing junk.
The parsed integer as an int. If there are no digits, return 0. Trailing non-digit characters are ignored.
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.
int my_atoi(const char *s) {
/* TODO */
return 0;
}
Overflowing an int while building the positive magnitude of INT_MIN.
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.