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 with an account.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);
}Tips
- 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.