zoukankan      html  css  js  c++  java
  • Leetcode 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.

    只需要考虑正负号,小数点,指数e符号,数字四种可能,除了它们之外的字符,程序返回false。

    • 正负号:只能出现在第一个字符或者e后面,不能出现在最后一个字符
    • 小数点:字符串不能只含有小数点,也不能只含正负号和小数点,小数点不能在e或者小数点后
    • e:e不能出现在第一个字符,也不能出现在最后一个字符,e前面不能没有数字,也不能有e
    class Solution {
    public:
        bool isVaild(char c){
            if(c=='+' || c=='-' || c == '.' || c=='e' || c>='0'&& c <= '9') return true;
            else return false;
            
        }
        
        bool isNumber(const char *s) {
            string str(s);
            bool res = false;
            size_t pos = str.find_first_not_of(" ");
            if(pos!=string::npos) str=str.substr(pos);     //去掉前端空格
            else str="";
            pos = str.find_last_not_of(" ");
            str=str.substr(0,pos+1);  //去掉后端空格
            if(str == "") return res;
            bool hasSign = false, hasDot = false, hasExp = false, hasDigit = false;
            int len = str.length();
            for(int i = 0 ; i < len ;++ i){
                char ch = str[i];
                if(!isVaild(ch)) return false;
                switch(ch){
                    case '+':
                    case '-':
                        //不在第一个或者e后面;在最后一个字符
                        if((i!=0 && str[i-1]!='e') || i== len-1) return false;
                        else hasSign = true;
                        break;
                    case '.':
                        //只有一个字符的情况;只有符号和点;在e和点之后
                        if(len == 1 || (len == 2 && hasSign) || hasExp || hasDot) return false;
                        else hasDot = true;
                        break;
                    case 'e':
                        //出现在第一个或最后一个;前面没有数字;前面有e
                        if(i == 0 || i == len-1 || !hasDigit || hasExp) return false;
                        else hasExp = true;
                        break;
                    default:
                        hasDigit = true;
                        break;
                }
            }
            return true;
        }
    };
  • 相关阅读:
    Java反编译代码分析(一)
    Java信号量Semaphore
    Ubuntu SVN安装&使用&命令
    Android -- Dialog动画
    Android -- EventBus使用
    Android -- queryIntentActivities
    解决:fatal: authentication failed for https
    MySQL表名大小写敏感导致的问题
    Publish to a Linux Production Environment
    layer.js 弹窗组件API文档
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3822944.html
Copyright © 2011-2022 走看看