Skip to content
thesarfo

Reference

String to Integer (atoi)

Implementing atoi from scratch — skipping whitespace, handling the sign, converting digits, and guarding against overflow before it happens.

views 0

Convert a string to an integer without using built-in parsing, handling the same edge cases as C’s atoi: leading spaces, an optional sign, invalid trailing characters, and overflow. (LeetCode problem)

Steps:

  1. Skip leading whitespace — increment an index until hitting a non-space character.
  2. Check for a sign — if the next character is + or -, record it (+1 or -1) and move the index forward; default to positive if there’s no sign.
  3. Convert characters to digits — while the current character is a digit, convert it via char - '0' (ASCII arithmetic).
  4. Handle overflow — before folding a digit into the running total, check whether total * 10 + digit would exceed Integer.MAX_VALUE/Integer.MIN_VALUE, and clamp if so, before doing the multiplication/addition (to avoid overflowing during the check itself).
  5. Return the result, multiplied by the sign.
class Solution {
public int myAtoi(String s) {
int index = 0, total = 0, sign = 1;
// Step 1: Ignore leading whitespace
while (index < s.length() && s.charAt(index) == ' ') {
index++;
}
// Step 2: Check for empty string after spaces
if (index == s.length()) return 0;
// Step 3: Check for sign
if (s.charAt(index) == '+' || s.charAt(index) == '-') {
sign = (s.charAt(index) == '-') ? -1 : 1;
index++;
}
// Step 4: Convert digits and handle overflow
while (index < s.length() && Character.isDigit(s.charAt(index))) {
int digit = s.charAt(index) - '0';
// Check if total will overflow after 10x + digit
if (total > (Integer.MAX_VALUE - digit) / 10) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
total = total * 10 + digit;
index++;
}
return total * sign;
}
}

Time: O(n). Space: O(1).

Condensed reference version of the overflow check, an equivalent way to write the same guard:

if (total > Integer.MAX_VALUE / 10 ||
(total == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10)) {
return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}

If total is already bigger than 214748364, multiplying by 10 will overflow. If total == 214748364 and digit > 7, it’ll also overflow. Clamp to Integer.MAX_VALUE (2147483647) if positive, Integer.MIN_VALUE (-2147483648) if negative.

Why multiply by sign at the end? "123" → total=123, sign=1 → 123. "-123" → total=123, sign=-1 → -123.

Pipeline summary: trim → sign → digits → clamp → sign multiply → return.