在字符串中找到第一个int范围内的数值 有限状态机

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

其中矩形是不接受状态,圆形是接受状态

#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;
}

猜你喜欢

转载自blog.csdn.net/sinat_37517996/article/details/105471014