Sword Finger Offer Question 20—a string representing a numeric value

A string representing a numeric value

Title: Please implement a function to determine whether a string represents a value (including integers and decimals).
For example, the string "+100", "5e2", "-123", "3.1416" and "-1E-16" all mean Numerical value,
but "12e", "1a3,14", "1.2.3", "±5" and "±5" and "12e5.4" are not

Representation mode

It can be concluded that the string pattern of the value represented is
A[.[B]][e|EC] or .B[e|EC]
where A is the integer part of the value, and B followed by the decimal point is the decimal part of the value. C immediately followed by'e' or'E' is the exponential part of the value.
There may be no integer part of the value in the decimal. For example, the decimal .123 is equal to 0.123. Therefore, the A part is not necessary. If a number does not have an integral part, then its decimal part cannot be empty. The
above A and C are both 0-9 digit strings that may start with "+" or "-"; B is also 0 ~ The digit string of 9, but there can be no sign in front

method

When judging whether a string conforms to the above pattern, first scan as many digits from 0 to 9 as possible (there may be a'+' or'-' at the beginning), that is, the money you buy in the pattern that represents a numeric integer Part A.
If it encounters a decimal point'.', start scanning the B part representing the decimal point of the value. If you encounter'e' or'E', start scanning part C

Code

bool isNumberic(const char* str)
{
    
    
	if(str==nullptr)
		return false;
	
	bool numeric=scanInteger(&str);
	
	//如果出现'.',则接下来时数字的小数部分
	if(*str=='.')
	{
    
    
		++str;
		/*下面一行代码用||的原因
		1、小数可以没有整数部分
		2、小数点后面可以没有数字,如233.和2333.0
		3、当然,小数点前面和后面可以都有数字,如2333.666
		*/
		numeric=scanUnsignedInteger(&str)||numeric;
		
	}
	//如果出现'e'或者'E',则接下来时数字的指数部分
	if(*str=='e' || *str=='E')
	{
    
    
		++str;
		/*下面一行用&&的原因
		1、当e或者E前面没有数字时,整个字符串并不能表示数字,如.e1、e1;
		2、当e或者E后面没有整数时,整个字符串不能表示数字,如12e、12e+5.4
		*/
		numeric==numeric&&scanInteger(&str);
	}
	return numeric && *str=='\0';
}

//用来扫描字符串中0~9的数位,可以用来匹配前面数值模式中的B部分
bool scanUnsignedInteger(const char** str)
{
    
    
	const char* before=*str;
	while(**str!='\0' && **str>='0' && **str<='9')
	++(*str);
	//当str中存在若干0~9的数字时,返回true
	return *str>before;
}
//扫描可能以表示正负的'+'或者'-'为起始的0~9的数位(类似一个可能带正负符号的整数)
bool scanInteger(const char** str)
{
    
    
	if(**str=='+' || **str=='-')
		++(*str);
	return scanUnsignedInteger(str);
}

———————————————————————————————————————————————— ————
Reference book "Sword Finger Offer"

Guess you like

Origin blog.csdn.net/rjszz1314/article/details/104240791