有效数字

来源:互联网 发布:西安软件开发工资水平 编辑:程序博客网 时间:2024/04/30 23:10

给定一个字符串,验证其是否为数字。


样例

"0" => true

" 0.1 " => true

"abc" => false

"1 a" => false

"2e10" => true

class Solution {public:    /**     * @param s the string that represents a number     * @return whether the string is a valid number     */    bool isNumber(string& s) {        // Write your code here        int n = s.length();    int begin = 0;    int end = n-1;    while (s[begin] == ' ')    {    begin++;    }    while (s[end] == ' ')    {    end--;    }        if (begin > end)        {            return false;        }    bool dotFound = false;    bool eFound = false;    bool numFound = false;    for (int i = begin; i <= end; i++)    {    if (s[i] <= '9' && s[i] >= '0')    {        numFound = true;    continue;    }    else if (s[i] == '.')    {        if (i == end)        {            return false;        }    else if (dotFound || eFound)    {    return false;    }    else    {    dotFound = true;    continue;    }    }    else if (s[i] == 'e')    {        if (!numFound || i == end)        {            return false;        }    else if (dotFound || eFound)    {    return false;    }    else    {    eFound = true;    continue;    }    }    else    {    return false;    }    }    return true;    }};



0 0
原创粉丝点击