## I. Title Description:

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 no character is read in because there is no leading space) Step 2: “42” (currently no character is read in because there is no ‘-‘ or ‘+’) Step 3: “42” (read in “42”) parses to the integer 42. Since “42” is in the range [-231, 231-1], the final result is 42.

Example 2:

Input: S = “-42″ Output: -42 Explanation: Step 1:” -42″ (read leading Spaces, but ignore them) Step 2: “-42″ (read ‘-‘ characters, so the result should be negative) Step 3:” -42″ (read “42”) parsed to the integer -42. Since “-42” is in the range [-231, 231-1], the final result is -42.

8. String conversion integer (AToi)

## Ii. Analysis of Ideas:

I used a trick to match it with the re. If no number is matched, 0 is returned. You just have to decide what the boundary values are.

## Iii. AC Code:

``````/ * * *@param {string} s
* @return {number}* /
var myAtoi = function(s) {
const input = s.trim();
let reg = new RegExp(/ ^ [\ + \]? \d+/g);
if(! reg.test(input)) {return 0
}
return Math.max(Math.min(input.match(reg)[0].Math.pow(2.31) - 1), Math.pow(-2.31));
};
Copy the code``````