Parse an integer
Parse an integer
Convert a decimal string such as "-123" to an int by hand. The task supplies valid input whose value fits in int.
Build a non-positive value digit by digit: result = result * 10 - digit. For "123", trace 0 → -1 → -12 → -123; negate at the end because the input was positive. A digit character becomes a number with c - '0'.
This matters at the negative limit. On the site's 32-bit int, INT_MIN is -2147483648, but 2147483648 does not fit. Building a positive magnitude first causes signed overflow. Keeping the intermediate value negative handles both limits under the stated preconditions.
This task is a function: use Check answer to run it with the checker’s different strings. The checker supplies main.
Difficulty 5/5 · 400 coins + a small bonus on first completion today
Complete int parse_int(const char *s) without conversion functions such as atoi. Input is a non-null, null-terminated string of one or more decimal digits with an optional leading -; its value fits in int, including INT_MIN and INT_MAX. No spaces, leading + or invalid input need handling.
Click Run to see the output here.