THN Interview Prep

008. String to Integer (atoi)

At a Glance

  • Topic: String
  • Pattern: Analyze Pattern
  • Difficulty: Medium
  • LeetCode: 008

Problem Statement

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.

The algorithm for myAtoi(string s) is as follows:

Whitespace: Ignore any leading whitespace (" ").
Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present.
Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.
Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1.

Return the integer as the final result.

Example 1:

Input: s = "42"

Output: 42

Explanation:

The underlined characters are what is read in and the caret is the current reader position. Step 1: &q...

Approach & Solution Steps

  • Brute force — regex capture — works but easy to miss edge cases.
  • Optimal — single linear scan with phase flags — O(length) time / O(1) space.

Optimal JS Solution

const INT32_MAX = 2147483647;
const INT32_MIN = -2147483648;

function myAtoi(input) {
	let index = 0;
	while (index < input.length && input[index] === ' ') {
		index++;
	}
	let sign = 1;
	if (index < input.length && (input[index] === '+' || input[index] === '-')) {
		if (input[index] === '-') {
			sign = -1;
		}
		index++;
	}
	let result = 0;
	while (index < input.length && input[index] >= '0' && input[index] <= '9') {
		const digit = input.charCodeAt(index) - '0'.charCodeAt(0);
		const maxDigit = sign === 1 ? 7 : 8;
		if (
			result > Math.trunc(INT32_MAX / 10) ||
			(result === Math.trunc(INT32_MAX / 10) && digit > maxDigit)
		) {
			return sign === 1 ? INT32_MAX : INT32_MIN;
		}
		result = result * 10 + digit;
		index++;
	}
	return sign * result;
}

Edge Cases & Pitfalls

  • Always consider empty or null inputs.
  • Watch out for off-by-one index errors.

Mark this page when you finish learning it.

Last updated on

Spotted something unclear or wrong on this page?

On this page