您的位置:首页 > 编程语言 > C语言/C++

[leetcode-65]Valid Number(C语言)

2015-07-13 21:52 656 查看
问题描述:

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.

代码分析:这道题巨**恶心,关键是有些规则并不清楚,需要一次一次的得到测试用例之后才知道规则。另外,这道题建议分开写,而不是混杂在一起,实在是太乱了。总的来说,如果存在e,那么e之前一定为一个float,后面为一个整数。如果不存在e,就检查整体是否为float。

代码如下:8ms

[code]bool checkFloat(char *s,int start,int end){
    if(start>end)
        return false;
    int i;
    int pointNums = 0;
    for(i = start;i<=end;i++){
        if(s[i]=='.'){
            pointNums++;

            if(start==end||pointNums>1)
                return false;
        }
        else if(s[i]<'0'||s[i]>'9')
            return false;
    }
    return true;
}
//闭区间
bool checkInt(char *s,int start,int end){
    if(start<=end&&(s[start]=='+'||s[start]=='-'))
        start++;
    if(start>end)
        return false;
    int i;
    for(i = start;i<=end;i++){
        if(s[i]<'0'||s[i]>'9')
            return false;
    }
    return true;
}
bool isNumber(char* s) {
    int i;
    int startIndex,endIndex;
    int length = strlen(s);

    //delete the space from head;
    for(startIndex = 0;startIndex<length;startIndex++)
        if(s[startIndex]!=' ')
            break;
    //delete the space from tail
    for(endIndex = length-1;endIndex>=0;endIndex--)
        if(s[endIndex]!=' ')
            break;
    //delete the +/1 from head
    while(startIndex<=endIndex&&(s[startIndex]=='+'||s[startIndex]=='-'))
        startIndex++;
    if(startIndex>endIndex)
        return false;

    for(i = startIndex;i<=endIndex;i++){
        if(s[i] == 'e'||s[i] == 'E'){
            bool tmp1 = checkFloat(s,startIndex,i-1);
            bool tmp2 = checkInt(s,i+1,endIndex);
            if(tmp1&&tmp2)
                return true;
            else
                return false;
        }
    }
    //没有e
    return checkFloat(s,startIndex,endIndex);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: