题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
参考《剑指offer》
表示数值的字符串遵循模式:A[.[B]][e|EC] 或者 .B[e|EC],其中A为数值的整数部分,B紧跟着小数点为数值的小数部分,C紧跟着e或者E为数值的指数部分。A[.[B]] 包含这几种情况:123、123.、123.45、.45
bool numeric = scanInteger(&str);
上面这行代码包含这种情况:123
numeric = scanUnsignedInteger(&str) || numeric;
上面这行代码包含了这三种情况(含有小数点时的情况):
1、小数可以没有整数部分,如.123等于0.123
2、小数点后面没有数字,如233.等于233.0
3、小数点前面和后面都有数字,如233.666
注意顺序不能反过来,否则由于或运算存在惰性求值,numeric为true的情况不会遍历小数点后的数字
class Solution {
public:
bool isNumeric(char* str)
{
if(str == nullptr)
return false;
bool numeric = scanInteger(&str);
if(*str == '.'){
str++;
//或操作的顺序不能变,很重要,如果交换,23.12,由于惰性求值,
//数字位12不会遍历
numeric = scanUnsignedInteger(&str) || numeric;
}
if(*str == 'e' || *str == 'E'){
str++;
numeric = numeric && scanInteger(&str);
}
return numeric && *str == '\0';
}
//扫描无符号的整数
bool scanUnsignedInteger(char** str){
char* before = *str;
while(**str != '\0' && **str >= '0' && **str <= '9')
++(*str);
return *str > before;
}
//扫描可能带正负号的整数
bool scanInteger(char** str){
if(**str == '+' || **str == '-')
(*str)++;
return scanUnsignedInteger(str);
}
}
官方答案:
class Solution {
public:
bool isNumeric(const char* str)
{
if(str == nullptr)
return false;
bool numeric = scanInteger(&str);
// 如果出现'.',接下来是数字的小数部分
if(*str == '.')
{
++str;
// 下面一行代码用||的原因:
// 1. 小数可以没有整数部分,例如.123等于0.123;
// 2. 小数点后面可以没有数字,例如233.等于233.0;
// 3. 当然小数点前面和后面可以有数字,例如233.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';
}
bool scanUnsignedInteger(const char** str)
{
const char* before = *str;
while(**str != '\0' && **str >= '0' && **str <= '9')
++(*str);
// 当str中存在若干0-9的数字时,返回true
return *str > before;
}
// 整数的格式可以用[+|-]B表示, 其中B为无符号整数
bool scanInteger(const char** str)
{
if(**str == '+' || **str == '-')
++(*str);
return scanUnsignedInteger(str);
}
};