[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.
要写对这题着实不容易,很多细节需要考虑。先看看测试用例有哪些,然后再写就比较有针对性。最后看看哪些test case错了,再修一下bug。
1 class Solution { 2 public: 3 bool isNumber(const char *s) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (s == NULL) 7 return false; 8 9 while(isspace(*s)) 10 s++; 11 12 if (*s == '+' || *s == '-') 13 s++; 14 15 bool eAppear = false; 16 bool dotAppear = false; 17 bool firstPart = false; 18 bool secondPart = false; 19 bool spaceAppear = false; 20 while(*s != '\0') 21 { 22 if (*s == '.') 23 { 24 if (dotAppear || eAppear || spaceAppear) 25 return false; 26 else 27 dotAppear = true; 28 } 29 else if (*s == 'e' || *s == 'E') 30 { 31 if (eAppear || !firstPart || spaceAppear) 32 return false; 33 else 34 eAppear = true; 35 } 36 else if (isdigit(*s)) 37 { 38 if (spaceAppear) 39 return false; 40 41 if (!eAppear) 42 firstPart = true; 43 else 44 secondPart = true; 45 } 46 else if (*s == '+' || *s == '-') 47 { 48 if (sapceAppear) 49 return false; 50 51 if (!eAppear || !(*(s-1) == 'e' || *(s-1) == 'E')) 52 return false; 53 } 54 else if (isspace(*s)) 55 spaceAppear = true; 56 else 57 return false; 58 59 s++; 60 } 61 62 if (!firstPart) 63 return false; 64 else if (eAppear && !secondPart) 65 return false; 66 else 67 return true; 68 } 69 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】