You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
89 lines
1.5 KiB
89 lines
1.5 KiB
3 years ago
|
/**
|
||
|
* @param {string} str
|
||
|
* @return {number}
|
||
|
*/
|
||
|
|
||
|
const numeric = /^[0-9]+$/;
|
||
|
|
||
|
var myAtoi = function(str) {
|
||
|
let value = 0;
|
||
|
let number = "";
|
||
|
|
||
|
if (str === null || str === ""){
|
||
|
return value;
|
||
|
}
|
||
|
|
||
|
let validNumber = true;
|
||
|
let positive = true;
|
||
|
let startParsing = false;
|
||
|
|
||
|
for (let i = 0; i < str.length; ++i){
|
||
|
|
||
|
let isSpace = /\s/.test(str.charAt(i));
|
||
|
let isNegative = (str.charAt(i) === '-');
|
||
|
let isPositive = (str.charAt(i) === '+');
|
||
|
let isNumeric = (numeric.test(str.charAt(i)));
|
||
|
|
||
|
let validChar = (isSpace || isNegative || isPositive || isNumeric);
|
||
|
|
||
|
if (validChar){
|
||
|
if (isNegative){
|
||
|
if (startParsing){
|
||
|
break;
|
||
|
}
|
||
|
positive = false;
|
||
|
startParsing = true;
|
||
|
}
|
||
|
|
||
|
if (isPositive){
|
||
|
if (startParsing){
|
||
|
break;
|
||
|
}
|
||
|
positive = true;
|
||
|
startParsing = true;
|
||
|
}
|
||
|
|
||
|
if (isSpace){
|
||
|
if (startParsing){
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (isNumeric){
|
||
|
number += str.charAt(i);
|
||
|
startParsing = true;
|
||
|
}
|
||
|
} else {
|
||
|
if (!startParsing){
|
||
|
validNumber = false;
|
||
|
}
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (validNumber){
|
||
|
|
||
|
if (number.length === 0){
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
let output = parseInt(number, 10);
|
||
|
|
||
|
if (output >= 2147483648){
|
||
|
if (positive){
|
||
|
output = 2147483647;
|
||
|
} else {
|
||
|
output = 2147483648;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (!positive){
|
||
|
output *= -1;
|
||
|
}
|
||
|
|
||
|
return output;
|
||
|
} else {
|
||
|
return 0;
|
||
|
}
|
||
|
};
|