Skip to content

String to Integer (atoi)

Problem

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

Input: s = "42"

Output: 42

Input: s = " -042"

Output: -42

Input: s = "1337c0d3"

Output: 1337

Input: s = "0-1"

Output: 0

Input: s = "words and 987"

Output: 0

wrong answer

what is wrong with this code

function myAtoi(s: string): number {
    s = s.trim();
    for (let i = 0; i < s.length; i++) {
        console.log(s[i]);
        if (!(Number.isInteger(s[i]) || s[i] == "-")) {
            return Number(s.substring(0, i));
        }
    }
    return Number(s) || 0;
}

here is the problem with the code:

  1. Number.isInteger(s[i]): this is wrong because s[i] is a string, not a number. You should use parseInt(s[i]) instead.

correct code:

function myAtoi(s: string): number {
    s = s.trim();
    for (let i = 0; i < s.length; i++) {
        console.log(s[i]);
        if (!(parseInt(s[i]) || s[i] == "-")) {
            return Number(s.substring(0, i));
        }
    }
    return Number(s) || 0;
}