This is the 12th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Topic describes

MyAtoi (string s) converts a string to a 32-bit signed integer (similar to atoi in C/C++).

MyAtoi (string s)

Read in the string and discard useless leading whitespace to check whether the next character (assuming it has not reached the end of the character) is a plus or minus sign and read that character (if any). Determine whether the final result is negative or positive. If neither exists, the result is assumed to be positive. Read 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 the previous steps to integers (that is, “123” -> 123, “0032” -> 32). If no number is read in, the integer is 0. Change symbols as necessary (starting with Step 2). If the number of integers exceeds the range of 32-bit signed integers [−231, 231 − 1], truncate the integer to keep it within the range. Specifically, integers less than −231 should be fixed to −231 and integers greater than 231 − 1 to 231 − 1. Returns an integer as the final result. Note:

Whitespace characters in this case include only the space character ‘ ‘. Do not omit any characters other than those following a leading space or number.

  • Example 1:
Input: s = "42" Output: 42 Description: The character string in bold is the character that has been read in, and the caret is the character that is currently read. Step 1: "42" (currently not read because there is no leading space) ^ Step 2: "42" (currently not read because there is no '-' or '+') ^ Step 3: "42" (read "42") ^ parses to the integer 42. Since "42" is in the range [-231, 231-1], the final result is 42.Copy the code
  • Example 2:
Input: s = "-42" Output: -42 Explanation: Step 1:" -42" (read leading space, but ignore it) ^ Step 2: "-42" (read '-' character, so result should be negative) ^ Step 3: "-42" (reading "42") ^ parses to the integer -42. Since "-42" is in the range [-231, 231-1], the final result is -42.Copy the code
  • Example 3:
Input: s = "4193 with words" Output: 4193 "4193 with words" (currently not read because there is no '-' or '+') ^ step 3: "4193 with words" (read "4193"; Since the next character is not a number, the reading is stopped) ^ parses to the integer 4193. Since "4193" is in the range [-231, 231-1], the final result is 4193.Copy the code
  • Example 4:
Input: s = "words and 987" Output: 0 Explanation: step 1: "Words and 987" (currently not read because there is no leading space) ^ Step 2: "Words and 987" (currently not read because there is no '-' or '+') ^ Step 3:" Words and 987" (reading stopped because the current character 'w' is not a number) ^ parse to the integer 0 because no number was read. Since 0 is in the range [-231, 231-1], the final result is 0.Copy the code
  • Example 5:
Input: s = "-91283472332" Output: -2147483648 Explanation: Step 1: "-91283472332" (currently no character is read because there is no leading space) ^ Step 2: "-91283472332" (reads the '-' character, so the result should be negative) ^ Step 3: "-91283472332" (reads "91283472332") ^ parses to the integer -91283472332. Since -91283472332 is less than the lower bound of the range [-231, 231-1], the final result is truncated to -231 = -2147483648.Copy the code
  • Tip:
` 0 < = s.l ength < = 200 ` ` s ` by English letters (uppercase and lowercase), number (` 0-9 `), ` '`, ` `, `' + ' '-' ` and `. ' '` compositionCopy the code

Implementation approach

Because the length of the string is limited, we can check the input string one by one and propose the integer that conforms to the question. First remove the space character at the end of the input character, and then take out the first part of the string to check. The overall rule is as follows:

  1. State is defined to indicate whether a number has been picked up. If a number has been picked up and a character that is not a number has been skipped, return res.
  2. If state = false, add ‘+’ or ‘-‘ to res first
  3. Return res after ‘+’, ‘-‘ and Spaces and other characters
  4. If you encounter a number in the loop, state is set to true, 0 is encountered if the beginning is empty or the sign is skipped to read the next bit, otherwise the number is added to the res, and you exit the loop until you encounter a character or the string is empty.
  5. Res returns 0 if it is not a number, returns the nearest value outside the boundary, and returns the number itself.
/ * * *@param {string} s
 * @return {number}* /
var myAtoi = function(s) {
    let res = ' '
    s = s.trim()
    let state = false
    while(s.length > 0) {
        let str = s[0]
        s = s.substring(1)
        if (str == ' ' || str == '+') {
            if (res == ' ' && !state) {
                res = str.trim()
                continue
            } else {
                break}}if (str == The '-') {
            if (res == ' ' && !state) {
                res = The '-'
                continue
            } else {
                break}}if (0 <= str && str <= 9) {
            state = true
            if (str == 0 && (res == The '-' || res == '+' || res == ' ')) {
                continue
            }
            res += str
        } else {
            break; }}if (res >= 2147483647) {
        return 2147483647
    } else if (res <= -2147483648) {
        return -2147483648
    } else if (isNaN(res)) {
        return 0
    }
    return res / 1
};
Copy the code

To sum up the above rules, we can directly solve the problem through regular expression:

/ * * *@param {string} s
 * @return {number}* /
var myAtoi = function(s) {
    s = s.trim()
    let reg = / ^ (- | \ +)? \d+/
    let res = s.match(reg)
    res = res ? res[0] : 0
    return  res > 0 ? Math.min(2147483647, res) : Math.max(-2147483648, res)
};
Copy the code