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;
    }
复制代码

 

posted @   咖啡中不塌缩的方糖  阅读(136)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 内存占用高分析
· .NET Core GC计划阶段(plan_phase)底层原理浅谈
· .NET开发智能桌面机器人:用.NET IoT库编写驱动控制两个屏幕
· 用纯.NET开发并制作一个智能桌面机器人:从.NET IoT入门开始
· 一个超经典 WinForm,WPF 卡死问题的终极反思
阅读排行:
· 20250116 支付宝出现重大事故 有感
· 一个基于 Roslyn 和 AvalonEdit 的跨平台 C# 编辑器
· 2025 最佳免费商用文本转语音模型: Kokoro TTS
· 在 .NET Core中如何使用 Redis 创建分布式锁
· 海康工业相机的应用部署不是简简单单!?
点击右上角即可分享
微信分享提示