The title

Title link: leetcode-cn.com/leetbook/re…



Answer key


1. Follow the instructions step by step

The problem has given the complete algorithm, follow the algorithm to become, there are the following points to pay attention to:

  • Processing outside the range of 32-bit signed integers;
  • ‘-+89’ or ‘+-980’ returns 0;
/ * * *@param {string} s
 * @return {number}* /
var myAtoi = function(s) {

    let index = 0,
        isMinus = false,
        integer = 0;

    const max_abs = Math.pow(2.31) - 1,
        min_abs = Math.pow(2.31);


    while(s[index] === ' '){
        index++;
    }

    if(s[index] === The '-'){
        index++;
        isMinus = true;
    }else if(s[index] === '+'){
        index++;
    }
    

    while(s[index] === '0') {
        index++;
    }

    while(s[index] <= '9' && s[index] >= '0') {

        integer = integer * 10 + Number(s[index]);
        if( integer > max_abs && false === isMinus) {
            return max_abs;
        }
        if( integer > min_abs && true === isMinus) {
            return 0 - min_abs;
        }
        index++;

    }

    if(integer ! = =0 && isMinus) {
        return -integer;
    }
    return integer;
};

Copy the code


2. Use the parseInt method given by JS Number

You can convert a string to an integer using the parseInt() method of the JavaScript Number object, but the rules for converting parseInt() are not exactly the same, so you need to modify the output.

  • ParseInt () outputs NaN for non-numeric characters, and 0 for unprocessable strings.
  • ParseInt () converts more than 32 – bit signed integers;
/ * * *@param {string} s
 * @return {number}* /
var myAtoi = function(s) {

    let n = parseInt(s);
    const max = Math.pow(2.31) - 1,
        min = 0 - Math.pow(2.31);

    if(n.toString() === 'NaN') {
        return 0;
    }else if( n < min) {
        return min;
    }else if( n > max ) {
        return max;
    }

    return n;
};
Copy the code


If you have a better way of thinking and reconciliation, welcome to discuss ah ~

This is a summary and implementation of each problem in LeetCode’s “Elementary Algorithms” using JavaScript. The summary is here:

Juejin. Cn/post / 700669…