• 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.

    public bool IsNumber(string s) {
            int size = s.Length;
            if(size == 0) return false;
            int numindex = -1; 
            int dotindex = -1;
            int eindex = -1;//e index
            var possibleFirstChar = new List<char>(){'+','-','.'};
             var digits = new List<char>(){'0','1','2','3','4','5','6','7','8','9'};
            if(size == 1 && !digits.Contains(s[0])) return false;
            //remove spaces at the beginning till not ' '
            int start = 0;
            while(start< size && s[start] == ' ')
            {
                start++;
            }
            if(start == size) return false;
            //first letter just
            if(!possibleFirstChar.Contains(s[start]) && !digits.Contains(s[start])) return false;
            if(possibleFirstChar.Contains(s[start]))
            {
                if(s[start] == '.') { 
                    dotindex = start;
                }
                start++;
            }
           
           
           
            int tempStart = start;
            int i =tempStart;
            for(;i<size && s[i] != ' ';i++)
            {
                if(s[i] == 'e') 
                {
                    if(eindex >= 0 || numindex < 0) return false;// cannot have 2 'e' && must have digits before e
                    eindex = i;
                }
                else if(s[i] == '.')
                {
                     if(eindex >= 0 || dotindex >= 0) return false; // cannot after '2' && can not have 2 '.'
                     dotindex = i;
                }
                else if(s[i] == '+' || s[i] == '-') //should be just after 'e'
                {
                    if( eindex != i-1) return false;
                }
                else if(!digits.Contains(s[i])) return false; 
                else numindex = i;
            }
            //check whether we have extra spaces in the end
            if(i != size)
            {
                while(i<size)
                {
                if(s[i] !=' ') return false;
                i++;
                }
            }//blank at end
            if((dotindex==0 && eindex == 1)) return false;// such as .e12;
            if(numindex < 0 || numindex < eindex) return false;// such as . , e; 
            return true;
        }
  • 相关阅读:
    青龙峡蹦极
    DNN Web Platform 官方汉化版本 5.5
    “\images” 和 “~\images'”的区别
    我们家的小公主
    asp实用类库DataList
    计算上月、下月、上周、下周..日期范围
    网页按钮大本营
    用XP做服务器突破10人限制
    变动翻屏展示图片效果
    写给所有的IT民工们
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5874186.html
Copyright © 2020-2023  润新知