• 65. Valid Number


    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.

    class Solution {
    public:
        bool isNumber(string s) {
            //trim
            s.erase(0,s.find_first_not_of(" "));
            s.erase(s.find_last_not_of(" ") + 1);
            int len = s.length();
            if(len==0) return false;
            bool dotFlag = false;
            bool eFlag = false;
            
            //check first letter
            if((s[0] < '0' || s[0] > '9') && s[0]!='+' && s[0]!='-' && s[0]!='.') return false;
            if(s[0]=='.') dotFlag = true;
            
            //check rest letters
            for(int i = 1; i < len; i++){
                if((s[i]=='+' || s[i]=='-') && s[i-1]=='e') continue; 
                if(s[i]=='.' && !dotFlag && !eFlag) {
                    dotFlag = true;
                    continue;
                }
                if(s[i]=='e'&& !eFlag){
                    eFlag = true;
                    if(s[i-1]=='.' && i >= 2 && (s[i-2]>= '0' && s[i-2] <= '9')) continue;
                    if (s[i-1]!='-' && s[i-1]!='+' && s[i-1]!='.') continue;
                } 
                if(s[i]>='0' && s[i] <='9') continue;
                return false;
            }
            
            //check last letter
            if(s[len-1]=='e' || s[len-1]=='+' || s[len-1]=='-' ){
                return false;
            }
            if(s[len-1]=='.' && ((len >= 2 && (s[len-2]< '0' || s[len-2] > '9')) ||len==1)) return false;
            return true;
        }
    };
  • 相关阅读:
    【统计学】第七章
    【统计学】第六章
    【统计学】第五章
    【统计学】第四章
    【统计学】第三章
    【统计学】第二章
    MYSQL基础
    股票数据Scrapy爬虫
    Scrapy爬虫基本使用
    Scrapy爬虫框架
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4928632.html
Copyright © 2020-2023  润新知