Skip to content
UniCircle
MediumCodingStrings and integer overflow

Write your own atoi with overflow clamping

Question C-STR-105

Write int my_atoi(const char *s) without calling atoi, strtol or sscanf. It reads a number from the start of a string using these rules:

  1. Skip leading spaces.
  2. Read an optional + or -.
  3. Read digits until the first non-digit character or the end of the string. Ignore everything after that.
  4. If no digits were read, the result is 0.
  5. If the value is outside the 32-bit signed range, clamp it: return 2147483647 if it is too large, −2147483648 if it is too small.

Apply it to T lines and print each result.

Constraints

  • 1 ≤ T ≤ 1000
  • Each string has at most 200 characters.

Input and output

Input
First line: T. Then T lines, each holding one string (it may be empty and may contain spaces).
Output
T lines, each with the integer result.

Examples

Input 1

5
42
   -17
4193 with words
words and 987
+0012

Output

42
-17
4193
0
12

"words and 987" starts with a letter, so the result is 0. Leading zeros are dropped.

Input 2

3
2147483648
-2147483648
-91283472332

Output

2147483647
-2147483648
-2147483648

Too large is clamped to INT_MAX. INT_MIN itself fits. The last value is clamped to INT_MIN.

Show hints
  • Overflow is undefined behaviour for signed int, so detect it before it happens, or build the value in a long long and cap it once it passes 2147483648.
  • " -0012ab" gives −12. "+-3" gives 0, because after the sign another sign is not a digit.
Show the explanation

Use a pointer p and scan once:

  1. while (*p == ' ') p++;
  2. If *p is + or -, record the sign and step past it. Only one sign is allowed.
  3. While *p is a digit, do v = v * 10 + (*p - '0').

Overflow is the real test. Signed overflow in C is undefined behaviour, so you cannot compute the value in an int and check afterwards. Two safe options:

  • Accumulate in a long long and cap v at 2147483648 as soon as it passes that value. The cap keeps the variable from overflowing on very long digit strings. At the end, sign * v is clamped to [INT_MIN, INT_MAX].
  • Or stay in int and check before multiplying: if v > (INT_MAX - d) / 10, the next step would overflow.

Edge cases to mention: an empty string, a sign with no digits, leading zeros ("0007" is 7), a space between the sign and the digits ("- 5" is 0), and −2147483648. Its magnitude is one more than INT_MAX, which is why the cap is 2147483648 and not 2147483647.

Original UniCircle question. Last reviewed 22 Oct 2026.