剑指offer-面试题20-表示数值的字符串-字符串

/*
题目:
	判断字符串是否表示数值。
*/
/*
思路:
	字符串遵循模式A[.[B]][e|EC] ,[+|-].B[e|EC]
	A、C为可能带正负号的数字串
	B为数字串
*/
#include<iostream>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<stdio.h>
using namespace std;

int index = 0;
bool scanUnsignedInteger(char *str){
    if(str[index] >= '0' && str[index] <= '9'){
        while(str[index] >= '0' && str[index] <= '9'){
            index++;
        }
        if(str[index] != '.' && str[index] != 'e' && str[index] != '\0' && str[index] != 'E'){
            return false;
        }
        return true;
    }
    return false;

}

bool scanInteger(char* str){
    if(str[index] == '+' || str[index] == '-'){
        index++;
    }
    return scanUnsignedInteger(str);
}

bool isNumeric(char* str)
{
     if(str == nullptr || *str == '\0'){
        return false;
     }
     bool numeric = true;

     if(str[index] != '.'){
        numeric = scanInteger(str);
        if(str[index] == '.'){
            index++;
            if(str[index] != 'e' && str[index] != 'E'){
                numeric = scanUnsignedInteger(str);
            }

        }
     }else {
        index++;
        numeric = scanUnsignedInteger(str);
     }
     if((str[index] == 'e' || str[index] == 'E') && numeric){
        index++;
        numeric = scanInteger(str);
     }
     return numeric && str[index]=='\0';
}


int main(){
    char* str = "100";
    cout<<isNumeric(str)<<endl;
}

   

猜你喜欢

转载自www.cnblogs.com/buaaZhhx/p/11892883.html