String to Integer (atoi)
Problem
Implement atoi which converts a string into a 32-bit signed integer. Skip leading whitespace, accept an optional '+' or '-' sign, then read consecutive digits and stop at the first non-digit. Clamp the result to [-2^31, 2^31 - 1].
" -42 with words"-42def my_atoi(s):
INT_MAX = 2**31 - 1
INT_MIN = -2**31
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
val = 0
while i < n and s[i].isdigit():
val = val * 10 + int(s[i])
i += 1
val *= sign
return max(INT_MIN, min(INT_MAX, val))
function myAtoi(s) {
const MAX = 2**31 - 1, MIN = -(2**31);
let i = 0, n = s.length;
while (i < n && s[i] === ' ') i++;
let sign = 1;
if (i < n && (s[i] === '+' || s[i] === '-')) {
sign = s[i] === '-' ? -1 : 1;
i++;
}
let val = 0;
while (i < n && s[i] >= '0' && s[i] <= '9') {
val = val * 10 + (s.charCodeAt(i) - 48);
i++;
}
val *= sign;
return Math.max(MIN, Math.min(MAX, val));
}
class Solution {
public 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) == '-')) {
sign = s.charAt(i) == '-' ? -1 : 1;
i++;
}
long val = 0;
while (i < n && Character.isDigit(s.charAt(i))) {
val = val * 10 + (s.charAt(i) - '0');
if (sign * val > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (sign * val < Integer.MIN_VALUE) return Integer.MIN_VALUE;
i++;
}
return (int)(sign * val);
}
}
int myAtoi(string s) {
int i = 0, n = s.size();
while (i < n && s[i] == ' ') i++;
int sign = 1;
if (i < n && (s[i] == '+' || s[i] == '-')) {
sign = s[i] == '-' ? -1 : 1;
i++;
}
long long val = 0;
while (i < n && isdigit(s[i])) {
val = val * 10 + (s[i] - '0');
if (sign * val > INT_MAX) return INT_MAX;
if (sign * val < INT_MIN) return INT_MIN;
i++;
}
return (int)(sign * val);
}
Explanation
This problem is really just copying what a human does when reading a number out of messy text: skip the blanks at the front, notice a plus or minus, then read digits until something that is not a digit shows up.
We use one index i that marches forward through the string in three phases. First, a loop advances past every leading space. Second, if the next character is '+' or '-', we record the sign and step past it. Third, while the current character s[i] is a digit, we build the number with val = val * 10 + digit.
The trick val * 10 + digit works because shifting the running total left by one decimal place and adding the new digit is exactly how place value works. For "42", we go 0 → 4 → 42.
At the end we multiply by sign and clamp the result into the 32-bit range with max(INT_MIN, min(INT_MAX, val)), so a giant number cannot overflow the allowed answer.
Example: " -42 with words". We skip three spaces, see '-' so sign = -1, read 4 then 2 to get 42, hit the space and stop, giving -42.