Bird
Raised Fist0
DSA Javascriptprogramming

String to Integer atoi in DSA Javascript

Choose your learning style10 modes available
Mental Model
Convert a string of characters into a number by reading each character one by one until a non-digit is found.
Analogy: Like reading a price tag from left to right, stopping when you see a letter or symbol that doesn't belong to the number.
string: "  -42abc"
index:  0 1 2 3 4 5 6
       ↑
number: 0
sign: +1
Dry Run Walkthrough
Input: string: " -42abc"
Goal: Convert the string to the integer -42 by ignoring spaces, reading sign, and digits until non-digit
Step 1: skip leading spaces
string: "  -42abc"
index:  0 1 2 3 4 5 6
           ↑
number: 0
sign: +1
Why: Spaces do not affect the number, so we move index to first non-space character
Step 2: read sign character '-'
string: "  -42abc"
index:  0 1 2 3 4 5 6
             ↑
number: 0
sign: -1
Why: Sign tells us if the number is positive or negative
Step 3: read digit '4' and update number to 4
string: "  -42abc"
index:  0 1 2 3 4 5 6
               ↑
number: 4
sign: -1
Why: First digit contributes to the number value
Step 4: read digit '2' and update number to 42
string: "  -42abc"
index:  0 1 2 3 4 5 6
                 ↑
number: 42
sign: -1
Why: Next digit adds to the number by shifting previous digits left
Step 5: encounter non-digit 'a', stop reading
string: "  -42abc"
index:  0 1 2 3 4 5 6
                   ↑
number: 42
sign: -1
Why: Non-digit means number parsing ends here
Result:
number: -42
Annotated Code
DSA Javascript
class Solution {
  myAtoi(s) {
    let i = 0, n = s.length, sign = 1, num = 0;
    // skip leading spaces
    while (i < n && s[i] === ' ') i++;
    // check sign
    if (i < n && (s[i] === '+' || s[i] === '-')) {
      sign = s[i] === '-' ? -1 : 1;
      i++;
    }
    // read digits
    while (i < n && s[i] >= '0' && s[i] <= '9') {
      num = num * 10 + (s[i].charCodeAt(0) - '0'.charCodeAt(0));
      i++;
    }
    return sign * num;
  }
}

// driver code
const sol = new Solution();
const input = "  -42abc";
console.log(sol.myAtoi(input));
while (i < n && s[i] === ' ') i++;
skip all leading spaces to find first meaningful character
if (i < n && (s[i] === '+' || s[i] === '-')) { sign = s[i] === '-' ? -1 : 1; i++; }
detect and record sign, then move index forward
while (i < n && s[i] >= '0' && s[i] <= '9') { num = num * 10 + (s[i].charCodeAt(0) - '0'.charCodeAt(0)); i++; }
convert digit characters to number by accumulating value
return sign * num;
apply sign to the accumulated number and return
OutputSuccess
-42
Complexity Analysis
Time: O(n) because we scan the string once from left to right
Space: O(1) because we use only a few variables regardless of input size
vs Alternative: Compared to parsing with built-in functions, this manual method controls parsing and stops at first invalid character, avoiding errors
Edge Cases
empty string
returns 0 because no digits found
DSA Javascript
while (i < n && s[i] >= '0' && s[i] <= '9') {
string with only spaces
returns 0 after skipping spaces and finding no digits
DSA Javascript
while (i < n && s[i] >= '0' && s[i] <= '9') {
string with no digits after sign
returns 0 because digits are required after sign
DSA Javascript
while (i < n && s[i] >= '0' && s[i] <= '9') {
When to Use This Pattern
When you need to convert a string to a number but must handle spaces, signs, and stop at invalid characters, use the String to Integer atoi pattern to parse carefully.
Common Mistakes
Mistake: Not skipping leading spaces before reading sign or digits
Fix: Add a loop to skip spaces before processing sign or digits
Mistake: Not stopping parsing when a non-digit character is found
Fix: Stop the digit reading loop as soon as a non-digit is encountered
Summary
Converts a string into an integer by reading characters until a non-digit is found.
Use when you must parse numbers from strings that may have spaces, signs, or trailing characters.
The key is to skip spaces, detect sign, read digits only, and stop at the first invalid character.

Practice

(1/5)
1. What is the main purpose of the atoi function in programming?
easy
A. Check if a string contains only digits
B. Convert an integer into a string
C. Sort characters in a string alphabetically
D. Convert a string representing a number into an integer

Solution

  1. Step 1: Understand the function name

    atoi stands for ASCII to integer, meaning it converts strings to integers.
  2. Step 2: Identify the function's purpose

    It takes a string input and returns its integer value if possible.
  3. Final Answer:

    Convert a string representing a number into an integer -> Option D
  4. Quick Check:

    atoi = string to integer conversion [OK]
Hint: Remember atoi means ASCII to integer conversion [OK]
Common Mistakes:
  • Confusing atoi with integer to string conversion
  • Thinking atoi sorts strings
  • Assuming atoi validates string digits only
2. Which of the following JavaScript code snippets correctly converts the string "123" to an integer using a method similar to atoi?
easy
A. const num = Number.toString("123");
B. const num = parseInt("123");
C. const num = "123".toString();
D. const num = "123" + 0;

Solution

  1. Step 1: Identify the correct conversion method

    parseInt converts a string to an integer in JavaScript, similar to atoi.
  2. Step 2: Check each option

    const num = parseInt("123"); uses parseInt correctly. const num = "123".toString(); converts string to string, no change. const num = Number.toString("123"); is invalid syntax. const num = "123" + 0; concatenates string and number, resulting in a string.
  3. Final Answer:

    const num = parseInt("123"); -> Option B
  4. Quick Check:

    parseInt("123") = 123 [OK]
Hint: Use parseInt() to convert string to integer [OK]
Common Mistakes:
  • Using toString() which returns a string
  • Trying Number.toString() incorrectly
  • Adding 0 to string results in string concatenation
3. What will be the output of the following JavaScript code?
function myAtoi(str) {
  let i = 0, sign = 1, result = 0;
  while (str[i] === ' ') i++;
  if (str[i] === '-' || str[i] === '+') {
    sign = str[i] === '-' ? -1 : 1;
    i++;
  }
  while (i < str.length && str[i] >= '0' && str[i] <= '9') {
    result = result * 10 + (str[i].charCodeAt(0) - '0'.charCodeAt(0));
    i++;
  }
  return sign * result;
}
console.log(myAtoi("  -42abc"));
medium
A. 0
B. 42
C. -42
D. NaN

Solution

  1. Step 1: Skip leading spaces and check sign

    The function skips spaces, finds '-', sets sign to -1, moves index forward.
  2. Step 2: Convert digits until non-digit

    Reads '4' and '2', converts to number 42, stops at 'a'.
  3. Step 3: Apply sign and return

    Returns -1 * 42 = -42.
  4. Final Answer:

    -42 -> Option C
  5. Quick Check:

    myAtoi(" -42abc") = -42 [OK]
Hint: Skip spaces, check sign, parse digits until non-digit [OK]
Common Mistakes:
  • Not skipping spaces before sign
  • Ignoring sign and returning positive number
  • Parsing non-digit characters
4. Identify the bug in this myAtoi function implementation:
function myAtoi(str) {
  let i = 0, sign = 1, result = 0;
  while (str[i] === ' ') i++;
  if (str[i] === '-' || str[i] === '+') {
    sign = str[i] === '-' ? -1 : 1;
    i++;
  }
  while (i < str.length && str[i] >= '0' && str[i] <= '9') {
    result = result * 10 + (str[i] - '0');
    i++;
  }
  return sign * result;
}
medium
A. Subtracting characters directly without charCodeAt causes NaN
B. Missing check for empty string input
C. Sign is not applied correctly
D. Loop does not skip spaces

Solution

  1. Step 1: Analyze digit conversion

    Expression str[i] - '0' tries to subtract strings, which results in NaN in JavaScript.
  2. Step 2: Correct approach

    Use str[i].charCodeAt(0) - '0'.charCodeAt(0) to get numeric value of digit character.
  3. Final Answer:

    Subtracting characters directly without charCodeAt causes NaN -> Option A
  4. Quick Check:

    String subtraction needs charCodeAt() [OK]
Hint: Use charCodeAt() to convert char digits to numbers [OK]
Common Mistakes:
  • Subtracting characters directly causing NaN
  • Not handling empty or invalid input
  • Ignoring sign application
5. You want to implement myAtoi that converts a string to a 32-bit signed integer. Which approach correctly handles overflow and returns the clamped value if the number is out of range?
function myAtoi(str) {
  let i = 0, sign = 1, result = 0;
  const INT_MAX = 2147483647;
  const INT_MIN = -2147483648;
  while (str[i] === ' ') i++;
  if (str[i] === '-' || str[i] === '+') {
    sign = str[i] === '-' ? -1 : 1;
    i++;
  }
  while (i < str.length && str[i] >= '0' && str[i] <= '9') {
    let digit = str[i].charCodeAt(0) - '0'.charCodeAt(0);
    if (result > Math.floor(INT_MAX / 10) || (result === Math.floor(INT_MAX / 10) && digit > INT_MAX % 10)) {
      return sign === 1 ? INT_MAX : INT_MIN;
    }
    result = result * 10 + digit;
    i++;
  }
  return sign * result;
}
hard
A. Correctly clamps overflow and returns 32-bit integer limits
B. Does not handle overflow, may return incorrect large numbers
C. Returns NaN on overflow instead of clamping
D. Ignores sign when clamping overflow values

Solution

  1. Step 1: Check overflow condition

    The code checks if adding the next digit causes overflow by comparing with INT_MAX/10 and last digit.
  2. Step 2: Return clamped value

    If overflow detected, returns INT_MAX or INT_MIN depending on sign, correctly clamping the value.
  3. Step 3: Otherwise accumulate result

    Accumulates digits safely within 32-bit integer range.
  4. Final Answer:

    Correctly clamps overflow and returns 32-bit integer limits -> Option A
  5. Quick Check:

    Overflow check and clamp = correct behavior [OK]
Hint: Check overflow before multiply, clamp to INT_MAX/INT_MIN [OK]
Common Mistakes:
  • Not checking overflow before multiplication
  • Returning wrong values on overflow
  • Ignoring sign when clamping
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard