题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
分析
各种情况分析:
1、小数
2、正负数
3、科学记数法
代码实现
bool isSign(char c) {
if (c =='+' || c == '-') {
return true;
}
return false;
}
bool isNum(char c) {
if (c <= 57 && c >= 48) {
return true;
}
else {
return false;
}
}
bool isNormalNum(char* str, int start, int end, bool*sign = NULL) {
if (start>end)
return false;
if (start == end)
return isNum(str[end]);
for (int ind = start; ind <= end; ind++) {
if (ind == start && (str[start] == '+' || str[start] == '-'))
{
if(sign)
*sign = true;
continue;
}
if (!isNum(str[ind]))
return false;
}
return true;
}
bool isPoint(char* str, int start, int end) {
int ind = 0;
for (ind = start; ind <= end; ind++) {
if (str[ind] == '.')
break;
}
if (ind == end)return false;
bool sign = false;
return (isNormalNum(str, start, ind - 1) ||
(ind == start) ||
(ind == start+1 && isSign(str[start]))
)
&&
(isNormalNum(str, ind + 1, end, &sign) && sign == false);
}
bool isExp(char* str, int start, int end) {
int ind = 0;
for (ind = start; ind <= end; ind++) {
if (str[ind] == 'E' || str[ind] == 'e')
break;
}
if (ind == end)return false;
return (isNormalNum(str, start, ind - 1) ||
isPoint(str, start, ind - 1)) &&
isNormalNum(str, ind + 1, end);
}
bool isNumeric(char* str, int start, int end) {
if (start == end)
return isNum(str[end]);
return isExp(str, start, end) ||
isPoint(str, start, end) ||
isNormalNum(str, start, end);
}
bool isNumeric(char* str) {
int n = strlen(str);
if (n == 0)
return false;
return isNumeric(str, 0, n - 1);
}
if (c =='+' || c == '-') {
return true;
}
return false;
}
bool isNum(char c) {
if (c <= 57 && c >= 48) {
return true;
}
else {
return false;
}
}
bool isNormalNum(char* str, int start, int end, bool*sign = NULL) {
if (start>end)
return false;
if (start == end)
return isNum(str[end]);
for (int ind = start; ind <= end; ind++) {
if (ind == start && (str[start] == '+' || str[start] == '-'))
{
if(sign)
*sign = true;
continue;
}
if (!isNum(str[ind]))
return false;
}
return true;
}
bool isPoint(char* str, int start, int end) {
int ind = 0;
for (ind = start; ind <= end; ind++) {
if (str[ind] == '.')
break;
}
if (ind == end)return false;
bool sign = false;
return (isNormalNum(str, start, ind - 1) ||
(ind == start) ||
(ind == start+1 && isSign(str[start]))
)
&&
(isNormalNum(str, ind + 1, end, &sign) && sign == false);
}
bool isExp(char* str, int start, int end) {
int ind = 0;
for (ind = start; ind <= end; ind++) {
if (str[ind] == 'E' || str[ind] == 'e')
break;
}
if (ind == end)return false;
return (isNormalNum(str, start, ind - 1) ||
isPoint(str, start, ind - 1)) &&
isNormalNum(str, ind + 1, end);
}
bool isNumeric(char* str, int start, int end) {
if (start == end)
return isNum(str[end]);
return isExp(str, start, end) ||
isPoint(str, start, end) ||
isNormalNum(str, start, end);
}
bool isNumeric(char* str) {
int n = strlen(str);
if (n == 0)
return false;
return isNumeric(str, 0, n - 1);
}