(Js) Leetcode 8. String conversion integer (atoi)

topic:

Please implement a myAtoi(string s) function to convert a string into a 32-bit signed integer (similar to the atoi function in C/C++).

The algorithm of the function myAtoi(string s) is as follows:

Read in the string and discard the useless leading spaces.
Check whether the first character (assuming the end of the character has not been reached) is positive or negative, and read the character (if any). Determine whether the final result is negative or positive. If neither exists, the result is assumed to be positive.
Read in the next character until the next non-numeric character is reached or the end of the input is reached. The rest of the string will be ignored.
Convert the numbers read in the previous steps to integers (ie, "123" -> 123, "0032" -> 32). If no number is read, the integer is 0. Change the symbol if necessary (from step 2).
If the integer number exceeds the 32-bit signed integer range [−231, 231 − 1], the integer needs to be truncated to keep it within this range. Specifically, integers less than −231 should be fixed to −231, and integers greater than 231 − 1 should be fixed to 231 − 1.
Return an integer as the final result.
note:

The blank characters in this question only include the space character ''.
Except for the leading space or the rest of the string after the number, do not ignore any other characters.

Ideas:

1. Remove spaces first

2. Empty, return 0

3. Judge the first character, if it is a sign, or a number, continue, otherwise return 0

    1) Traverse the string and find the position of the first character that is not a number

    2) Intercept the string of the digital part

4. Determine the upper and lower bounds of the digital part, and return the corresponding limit value if the limit is exceeded

Code:

/**
 * @param {string} s
 * @return {number}
 */
var myAtoi = function(s) {
    s = s.trim();
    if(!s) return 0;
    // 第一个字符是正负号,或者是数字
    if(['+','-'].includes(s[0]) || !isNaN(+s[0])) {
        for(let i = 1; i < s.length; i++) {
            // 找到某个数不是数字
            if(isNaN(+s[i]) || s[i] == ' ') {
                s = +s.substr(0, i);
            }
        }
        const max = Math.pow(2, 31) - 1;
        const min = Math.pow(-2, 31);
        +s < min && (s = min);
        +s > max && (s = max);
        return isNaN(+s) ? 0 : +s;
    }
    return 0;
};

operation result:

Guess you like

Origin blog.csdn.net/M_Eve/article/details/113622079