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:
- Skip leading spaces.
- Read an optional
+or-. - Read digits until the first non-digit character or the end of the string. Ignore everything after that.
- If no digits were read, the result is 0.
- 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
+0012Output
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
-91283472332Output
2147483647
-2147483648
-2147483648Too 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 along longand 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:
while (*p == ' ') p++;- If
*pis+or-, record the sign and step past it. Only one sign is allowed. - While
*pis a digit, dov = 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 longand capvat 2147483648 as soon as it passes that value. The cap keeps the variable from overflowing on very long digit strings. At the end,sign * vis clamped to[INT_MIN, INT_MAX]. - Or stay in
intand check before multiplying: ifv > (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.
