Skip to content

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.

Log in or create account

IGCSE, A-Level & AP