Code
/**
* @param {string} str
* @return {number}
*/
var myAtoi = function(str) {
let map = [
[0,1,2,3],
[3,3,2,3],
[3,3,2,3],
]
let reg =/[0-9]/
let r='';
let state = 0;
for(let i=0,l=str.length;i<l;i++){
if(str[i]==' '){
state = map[state][0];
}else if(str[i]=='+'||str[i]=='-'){
state = map[state][1];
}else if(reg.test(str[i])){
state = map[state][2];
}else{
state = map[state][3];
}
if(state==0){
continue
}
if(state==1||state==2){
r +=str[i]
}
if(state==3){
break
}
}
if(r==''||r=='-'||r=='+') return 0;
let num = Number(r);
if (num > 2147483647) {
return 2147483647
}
if (num < -2147483648) {
return -2147483648
}
return num
};
Ideas
In fact, all situations are considered as jumps between various states, as shown in the following table
air | +/- | digital | other | |
---|---|---|---|---|
Start | Start | Presence symbol | Digital conversion | End |
Presence symbol | End | End | Digital conversion | End |
Digital conversion | End | End | Digital conversion | End |
End | End | End | End | End |
When encountering four situations in the starting state, switch to the corresponding state to continue to the next character and so on
Example: 开始状态
the touch +/-
becomes 存在符号
a state