Valid Number

来源:互联网 发布:js 实现文档预览功能 编辑:程序博客网 时间:2024/06/03 16:58

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.
别人写的

bool isNumber(char* s)  {        if(s == NULL)            return false;        int i = 0;        //Skip leading spaces.        while(s[i] == ' ') i++;        //Significand        if(s[i] == '+' || s[i] == '-') i++;        int cnt = 0;        //Integer part        while(isdigit(s[i]))        {            i++;            cnt++;        }        //Decimal point        if(s[i] == '.') i++;        //Fractional part        while(isdigit(s[i]))        {            i++;            cnt++;        }        if(cnt == 0) return false;  //No number in front or behind '.'        //Exponential        if(s[i] == 'e')        {            i++;            if(s[i] == '+' || s[i] == '-') i++;            if(!isdigit(s[i])) return false;    //No number follows            while(isdigit(s[i])) i++;        }        //Skip following spaces;        while(s[i] == ' ') i++;        return s[i] == '\0';    }