2014.2.27 01:36
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.
Solution:
This is indeed a boring problem. You'll have to be careful with all the possibilities you have in mind.
Here are a few things to take care of:
1. "3." is valid
2. ".49" is valid
3. "2E12" and "-2e-2" are valid, but "E3" is not
4. "000123" is valid
5. "999999999999999999999999999999999" is valid, despite it being well beyond INT_MAX
There're surely other rules to check, but the few cases mentioned above are, in my opinion, more likely to be overlooked.
Total time complexity is O(len(s)). Space complexity is O(1).
Accepted code:
1 // 1CE, 3WA, 1AC, good, but not good enough. 2 #include <cstring> 3 using namespace std; 4 5 class Solution { 6 public: 7 bool isNumber(const char *s) { 8 int i, len; 9 10 if (s == nullptr) { 11 return false; 12 } 13 14 len = strlen(s); 15 // skip the trailing spaces 16 while (len - 1 >= 0 && s[len - 1] == ' ') { 17 --len; 18 } 19 i = 0; 20 21 // skip the leading spaces 22 while (i < len && s[i] == ' ') { 23 ++i; 24 } 25 if (i == len) { 26 return false; 27 } 28 29 // an optional sign 30 if (s[i] == '-' || s[i] == '+') { 31 ++i; 32 } 33 if (i == len) { 34 return false; 35 } 36 37 // the part before 'e' or 'E' 38 int dot_count = 0; 39 int digit_count = 0; 40 while (i < len && s[i] != 'e' && s[i] != 'E') { 41 if (s[i] >= '0' && s[i] <= '9') { 42 ++digit_count; 43 } else if (s[i] == '.') { 44 if (dot_count > 0) { 45 return false; 46 } else { 47 ++dot_count; 48 } 49 } else { 50 return false; 51 } 52 ++i; 53 } 54 if (i == len) { 55 // no 'e' or 'E' 56 if (digit_count > 0) { 57 return true; 58 } else { 59 return false; 60 } 61 } else if (digit_count == 0) { 62 return false; 63 } 64 65 ++i; 66 if (i == len) { 67 // no exponent after 'e' or 'E' 68 // 1.2E 69 return false; 70 } 71 72 if (s[i] == '-' || s[i] == '+') { 73 ++i; 74 } 75 if (i == len) { 76 // no digit after 'e' or 'E' 77 // 1.2E+ 78 // 1.3e- 79 return false; 80 } 81 while (i < len) { 82 if (s[i] >= '0' && s[i] <= '9') { 83 ++i; 84 } else { 85 return false; 86 } 87 } 88 89 return true; 90 } 91 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)