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.
Update (2014-12-06):
New test cases had been added. Thanks unfounder‘s contribution.
确认输入的字符串是否为一个数值,一系列的判断,主要是一些位置的判断:
- 输入前置空格
- 正负号
- 连续的数值,包括‘.’
- 符号e
- 正负号
- 连续数值,不包括‘.‘
- 后续空格
按上面的规则便行。
#include <iostream> using namespace std; class Solution { public: bool isNumber(const char *s) { int idx =0; for(;s[idx]==‘ ‘;idx++); if(s[idx]==‘-‘||s[idx]==‘+‘) idx++; int Point=0,Num=0; for(;(s[idx]>=‘0‘&&s[idx]<=‘9‘)||s[idx]==‘.‘;idx++) s[idx]==‘.‘?Point++:Num++; if(Point>1||Num<1) return false; if(s[idx]==‘e‘){ idx++; if(s[idx]==‘-‘||s[idx]==‘+‘) idx++; Num=0; for(;s[idx]>=‘0‘&&s[idx]<=‘9‘;idx++) Num++; if(Num<1) return false; } for(;s[idx]==‘ ‘;idx++); return s[idx]==‘\0‘; } }; int main() { char a[]="-e-"; Solution sol; cout<<sol.isNumber(a)<<endl; return 0; }
时间: 2024-10-05 01:08:46