Please implement a myAtoi(String s) function that converts a string to a 32-bit signed integer (similar to the AToi function in C/C++).

  • Read the string and discard useless leading Spaces
  • Check if the next character (assuming it is not at the end of the character) is a positive or negative sign and read the character (if any). Determine whether the final result is negative or positive. If neither is present, the result is assumed to be positive.
  • Reads the next character until the next non-numeric character is reached or the end of the input is reached. The rest of the string is ignored.
  • Convert the numbers read in in the previous step to integers (that is, “123” -> 123, “0032” -> 32). If no number is read, the integer is 0. Change the symbol if necessary (starting with Step 2).
  • If the number of integers exceeds the 32-bit signed integer range [−231, 231 − 1], truncate the integer 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.
  • Returns an integer as the final result.

Note:

  • Whitespace characters in this topic include only the space character' ' 。
  • Do not ignore any characters except the leading space or the rest of the string after a number.

Train of thought

  1. Return 0 if it is NaN (i.e., NaN in English before the number)
  2. The second is to judge whether it is'+' The '-'(That is, before numbers'+'Or minusThe '-')
  3. According to the'+' The '-'To determine whether it is greater than
Math.pow(2, 31) -1) return math.pow (2, 31) -1Copy the code
  1. According to the'+' The '-'Is less than
Math.pow(2, 31) return math.pow (2, 31)Copy the code

Code implementation

var myAtoi = function (s) {

    let a = parseInt(s, 10);
    if (isNaN(a)) {
        return 0;
    } else {
        if (a >= Math.pow(2, 31) - 1) {
            return Math.pow(2, 31) - 1;
        }
        if (a <= Math.pow(-2, 31)) {
            return Math.pow(-2, 31);
        }
    }
    return a;
};
Copy the code

We’re using parseInt to see if it’s a positive integer and we’re using Math

How to use and understand Math

Math is a Math function, but is an object data type. Typeof Math => ‘object’ console.dir(Math) View all function methods for Math. Math.pow() gets the power of a value

The use of the parseInt