This problem is more important for the understanding of the question, the first is to remove the blank space, the second is the judgment of plus or minus Followed by the transition Then judge whether the number of the conversion over here should you can think of a parseInt () function, which satisfies the first three, the last one is not satisfied, so only need to be done on the basis of a judgment.
var myAtoi = function(s) {
var getNum = function(num) {
if (num >= -Math.pow(2.31) && num <= Math.pow(2.31) -1) {
return num;
}else {
return num > 0 ? Math.pow(2.31) -1 : -Math.pow(2.31); }};let res = parseInt(s);
if (isNaN(res)) {
return 0;
} else {
returngetNum(res); }};Copy the code
It’s important to note that if parseInt fails, it will return NAN, which is understandable because; ParseInt is converted to number, and will naturally be converted to NAN if the conversion fails.
The second way to think about using regular expressions is to first look at one use of regular expressions for judging strings
Explain the expression ^ said begin with what, (+) – |? It’s either a minus sign or a plus sign, it’s either a zero or a one. \d+ : \d means several times, and + means at least one occurrence.
var myAtoi = function(s) {
let res = s.trim().match(/ ^ (- | \ +)? \d+/g);
return res ? Math.max(Math.min(res[0].Math.pow(2.31) -1), -Math.pow(2.31)) : 0;
};
Copy the code