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; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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 创建分布式锁
· 海康工业相机的应用部署不是简简单单!?