现在的位置: 首页 > 综合 > 正文

Valid Number

2017年12月23日 ⁄ 综合 ⁄ 共 1234字 ⁄ 字号 评论关闭

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.

 

根据OJ测试集的反馈,原本觉得应该合理的 2e e10,即e的指数还带e的情况是不算valid的,还有e的指数为小数也是不行的,所以最后的代码反而简单多了。

 

#include<iostream>
#include<vector>
#include<string>
#include<cstdio>
using namespace std;

bool foundBlock=false;

bool isValid(const char* s)
{
	int i=0;
	if (!s[i])
		return false;
	bool foundDot=false;
	bool numBeforeDot=false,numAfterDot=false;
	bool hasSig=false;
	if(s[i]=='+'||s[i]=='-')
	{
		hasSig=true;
		i++;
	}
	
	while(s[i])
	{
		if( '0'<=s[i]&& '9'>=s[i])
		{
			if( foundBlock) 
				return false;
			foundDot?numAfterDot=true:numBeforeDot=true;
		}
		else if ('.'==s[i])
		{
			if( foundDot || foundBlock)
				return false;
			else
				foundDot=true;
		}
		else if ('e'==s[i]||'E'==s[i]||foundBlock)
		{
			return isValid(&s[++i]);
		}
		else if (' '==s[i])
		{
			foundBlock=true;
		}
		else
			return false;
		i++;
	}
	if (foundDot)
	{
		if( !numBeforeDot || !numAfterDot)
			return false;
	}
	if (foundBlock)
	{
		if (!numBeforeDot)
			return false;
	}
	if (hasSig&&!numBeforeDot)
		return false;
	return true;
}

bool isNumber(const char* s)
{
	if (!s || !s[0])
		return false;
	foundBlock=false;
	int i=0;
	while(s[i]&&s[i]==' ')
		i++;
	return isValid(&s[i]);
}
int main()
{
	char s[10000];
	while(gets(s))
	{
		foundBlock=false;
		bool ans= isNumber(s);
		cout <<ans <<endl;
	}
}

【上篇】
【下篇】

抱歉!评论已关闭.