class Solution:
def myAtoi(self, s: str) -> int:
i = 0
n = len(s)
INT_MAX = 2**31 - 1
INT_MIN = -2**31
# 1. Skip leading whitespaces
while i < n and s[i] == ' ':
i += 1
# 2. Check for sign
sign = 1
if i < n and (s[i] == '+' or s[i] == '-'):
if s[i] == '-':
sign = -1
i += 1
# 3. Convert digits to integer
num = 0
while i < n and s[i].isdigit():
digit = int(s[i])
# 4. Check for overflow
if num > (INT_MAX - digit) // 10:
return INT_MAX if sign == 1 else INT_MIN
num = num * 10 + digit
i += 1
return sign * num
class Solution {
public:
int myAtoi(string s) {
int i = 0, n = s.size();
int sign = 1;
long num = 0;
const int INT_MAX = 2147483647;
const int INT_MIN = -2147483648;
// 1. Skip leading whitespaces
while (i < n && s[i] == ' ') i++;
// 2. Check for sign
if (i < n && (s[i] == '+' || s[i] == '-')) {
sign = (s[i] == '-') ? -1 : 1;
i++;
}
// 3. Convert digits to integer
while (i < n && isdigit(s[i])) {
int digit = s[i] - '0';
if (num > (INT_MAX - digit) / 10) {
return sign == 1 ? INT_MAX : INT_MIN;
}
num = num * 10 + digit;
i++;
}
return sign * num;
}
};
class Solution {
public int myAtoi(String s) {
int i = 0, n = s.length();
int sign = 1;
long num = 0;
int INT_MAX = Integer.MAX_VALUE;
int INT_MIN = Integer.MIN_VALUE;
// 1. Skip leading whitespaces
while (i < n && s.charAt(i) == ' ') i++;
// 2. Check for sign
if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
sign = (s.charAt(i) == '-') ? -1 : 1;
i++;
}
// 3. Convert digits to integer
while (i < n && Character.isDigit(s.charAt(i))) {
int digit = s.charAt(i) - '0';
if (num > (INT_MAX - digit) / 10) {
return sign == 1 ? INT_MAX : INT_MIN;
}
num = num * 10 + digit;
i++;
}
return (int) (sign * num);
}
}
var myAtoi = function(s) {
let i = 0, n = s.length;
let sign = 1, num = 0;
const INT_MAX = 2 ** 31 - 1;
const INT_MIN = -(2 ** 31);
// 1. Skip leading whitespaces
while (i < n && s[i] === ' ') i++;
// 2. Check for sign
if (i < n && (s[i] === '+' || s[i] === '-')) {
sign = s[i] === '-' ? -1 : 1;
i++;
}
// 3. Convert digits to integer
while (i < n && s[i] >= '0' && s[i] <= '9') {
let digit = s[i] - '0';
if (num > (INT_MAX - digit) / 10) {
return sign === 1 ? INT_MAX : INT_MIN;
}
num = num * 10 + digit;
i++;
}
return sign * num;
};
The "String to Integer (atoi)" problem asks you to convert a string s
to a 32-bit signed integer, following these rules:
[-2^31, 2^31 - 1]
), clamp the value to that range.The goal is to parse the string according to these rules and return the resulting integer.
The problem seems simple at first, but there are several edge cases to consider, such as handling whitespace, optional signs, invalid characters, and integer overflow. A naive approach might try to use built-in conversion functions, but these won't handle all the edge cases or the overflow requirements.
Instead, we need to process the string character by character, making decisions at each step. Brute-force would involve trying to convert the entire string and then checking for errors, but that's risky and may not handle all scenarios.
The optimized approach is to:
We use simple variables to track the current position, sign, and accumulated number. Checking for overflow before adding a new digit ensures we never exceed the allowed range.
Let's walk through the input " -42abc"
:
sign = -1
, move index to 4.num = 4
.num = 4 * 10 + 2 = 42
.result = -1 * 42 = -42
.-42
.
The function returns -42
, as expected.
The optimized approach is as efficient as possible for this problem.
The "String to Integer (atoi)" problem is a classic parsing challenge that requires careful attention to edge cases. By processing the string step-by-step—skipping whitespace, checking for a sign, reading digits, and handling overflow—we ensure robust behavior. The solution is efficient (O(n) time, O(1) space), elegant, and handles all specified constraints without relying on built-in conversion utilities.