Find the first numerical finite state machine in the range of int in the string

非0数字
0或非数字
遇到数字且结果未溢出
遇到数字且结果溢出
非数字
数字
非数字
S0
S1 开始计算数值
S3
S2 输出结果

Among them, the rectangle is not accepted, and the circle is accepted

#include <cstdio>
#include <cctype>

void compute(char c, int &ans);

int main(){
    
    
    int state = 0, ans = 0;
    char c;
    bool ans_found = false;
    while(scanf("%c", &c)!=EOF){
    
    
        if(ans_found) break;
        switch(state){
    
    
            case 0 : if(isdigit(c) && c!='0'){
    
    
                        state = 1;
                        compute(c, ans);
                     }
                     break;
            case 1 : if(isdigit(c)){
    
    
                        compute(c, ans);
                        if(ans<0){
    
    
                            state = 3;
                            ans = 0;
                        }
                     }
                     else state = 2;
                     break;
            case 2 : ans_found = true;
                     break;
            case 3 : if(!isdigit(c)) state = 0;
                     break;
            default : break;
        }
    }
    if(state==0 || state==3) printf("-1");
    else printf("%d", ans);
    return 0;
}

void compute(char c, int &ans){
    
    
    ans = ans * 10 + (c-'0');
    return;
}

Guess you like

Origin blog.csdn.net/sinat_37517996/article/details/105471014