Validate if a given string is numeric.

Some examples:
“0” => true
” 0.1 ” => true
“abc” => false
“1 a” => false
“2e10” => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

typedef enum States{
    Start,Start1,Int,FFlt,Flt,E,E1,Ee,End
} Sta;
typedef struct edge{
    Sta s,d;
    char *ac_inputs;
} Edge;
typedef struct StateNode{
    Sta c_st;
    Edge *edges;
    int edges_size;
} StaNode;
bool Accept_input(StaNode * st,char c){
    for(int i=0;i<st->edges_size;i++){
        if(st->edges[i].s==st->c_st){
            char *p=st->edges[i].ac_inputs;
            while(*p!='\0'){
                if(*p==c) {
                    st->c_st=st->edges[i].d;
                    return true;
                }
                p++;
            }
        }
    }
    return false;
}
bool isNumber(char* s) {
    
    StaNode st;
    st.edges_size=20;
    st.edges=(Edge *) malloc(sizeof(Edge)*st.edges_size);
    st.edges[0].s=Start;st.edges[0].d=Int;st.edges[0].ac_inputs="0123456789";
    st.edges[1].s=Start;st.edges[1].d=FFlt;st.edges[1].ac_inputs=".";
    st.edges[2].s=Int;st.edges[2].d=Flt;st.edges[2].ac_inputs=".";
    st.edges[3].s=Flt;st.edges[3].d=Flt;st.edges[3].ac_inputs="0123456789";
    st.edges[4].s=Int;st.edges[4].d=Int;st.edges[4].ac_inputs="0123456789";
    st.edges[5].s=Int;st.edges[5].d=E;st.edges[5].ac_inputs="e";
    st.edges[6].s=Flt;st.edges[6].d=E;st.edges[6].ac_inputs="e";
    st.edges[7].s=E;st.edges[7].d=Ee;st.edges[7].ac_inputs="0123456789";
    st.edges[8].s=Ee;st.edges[8].d=Ee;st.edges[8].ac_inputs="0123456789";
    st.edges[9].s=FFlt;st.edges[9].d=Flt;st.edges[9].ac_inputs="0123456789";
    st.edges[10].s=Start;st.edges[10].d=Start;st.edges[10].ac_inputs=" ";
    st.edges[11].s=Flt;st.edges[11].d=End;st.edges[11].ac_inputs=" ";
    st.edges[12].s=Int;st.edges[12].d=End;st.edges[12].ac_inputs=" ";
    st.edges[13].s=Ee;st.edges[13].d=End;st.edges[13].ac_inputs=" ";
    st.edges[14].s=End;st.edges[14].d=End;st.edges[14].ac_inputs=" ";
    st.edges[15].s=E;st.edges[15].d=E1;st.edges[15].ac_inputs="+-";
    st.edges[16].s=E1;st.edges[16].d=Ee;st.edges[16].ac_inputs="0123456789";
    st.edges[17].s=Start;st.edges[17].d=Start1;st.edges[17].ac_inputs="+-";
    st.edges[18].s=Start1;st.edges[18].d=Int;st.edges[18].ac_inputs="0123456789";
    st.edges[19].s=Start1;st.edges[19].d=FFlt;st.edges[19].ac_inputs=".";
    st.c_st=Start;
    while(*s!='\0'){
        if(!Accept_input(&st,*s)) return false;s++;
    }
    return st.c_st==Flt||st.c_st==Int||st.c_st==Ee||st.c_st==End;
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据