String to integer (atoi)
Skip leading spaces, read an optional sign, consume digits while clamping the running value, and stop at the first non-digit.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
The parse happens in strict stages: spaces, then one optional sign, then digits. A long accumulator means the running value can safely grow past int range before being clamped, instead of overflowing silently like an int would.
Code
public static int MyAtoi(string s) {
int i = 0, n = s.Length;
while (i < n && s[i] == ' ') i++;
int sign = 1;
if (i < n && (s[i] == '+' || s[i] == '-')) { if (s[i] == '-') sign = -1; i++; }
long result = 0;
while (i < n && char.IsDigit(s[i])) {
result = result * 10 + (s[i] - '0');
if (result * sign > int.MaxValue) return int.MaxValue;
if (result * sign < int.MinValue) return int.MinValue;
i++;
}
return (int)(result * sign);
}static int myAtoi(String s) {
int i = 0, n = s.length();
while (i < n && s.charAt(i) == ' ') i++;
int sign = 1;
if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) { if (s.charAt(i) == '-') sign = -1; i++; }
long result = 0;
while (i < n && Character.isDigit(s.charAt(i))) {
result = result * 10 + (s.charAt(i) - '0');
if (result * sign > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (result * sign < Integer.MIN_VALUE) return Integer.MIN_VALUE;
i++;
}
return (int) (result * sign);
}int myAtoi(const string& s) {
int i = 0, n = (int)s.size();
while (i < n && s[i] == ' ') i++;
int sign = 1;
if (i < n && (s[i] == '+' || s[i] == '-')) { if (s[i] == '-') sign = -1; i++; }
long long result = 0;
while (i < n && isdigit((unsigned char)s[i])) {
result = result * 10 + (s[i] - '0');
if (result * sign > INT_MAX) return INT_MAX;
if (result * sign < INT_MIN) return INT_MIN;
i++;
}
return (int)(result * sign);
}INT_MAX, INT_MIN = 2**31 - 1, -2**31
def my_atoi(s: str) -> int:
i, n = 0, len(s)
while i < n and s[i] == " ": i += 1
sign = 1
if i < n and s[i] in "+-": sign = -1 if s[i] == "-" else 1; i += 1
result = 0
while i < n and s[i].isdigit():
result = result * 10 + (ord(s[i]) - ord("0"))
if result * sign > INT_MAX: return INT_MAX
if result * sign < INT_MIN: return INT_MIN
i += 1
return result * signTips
- Clamp as soon as the running value crosses the limit; do not wait until the whole string is read.
- Any character that is not a digit, including right after the sign, simply ends the number early rather than causing an error.
In the .NET library
int.Parse throws on exactly the malformed input this problem expects you to handle gracefully, which is why atoi is written by hand instead of calling it.