表示数值的字符串
题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
思路
- 数值的结构是‘+/-‘ + ‘整数‘ + ‘.‘ + ‘整数‘ + ‘E/e‘ + ‘+/-‘ + ‘整数‘
- 按结构一个个的匹配,如果用if语句可以只匹配一次
代码
public class Solution {
public boolean isNumeric(char[] str) {
if (str == null || str.length == 0) {
return false;
}
int point = 0;
int length = str.length;
if (str[0] == ‘-‘ || str[0] == ‘+‘) {
point++;
}
boolean result = true;
while (point < length && str[point] >= ‘0‘ && str[point] <= ‘9‘) {
point++;
}
if (point < length) {
if (str[point] == ‘.‘) {
point++;
while (point < length && str[point] >= ‘0‘ && str[point] <= ‘9‘) {
point++;
}
if (point == length) {
return true;
}
if (str[point] == ‘e‘ || str[point] == ‘E‘) {
result = isE(str, point);
}else {
return false;
}
} else if (str[point] == ‘e‘ || str[point] == ‘E‘) {
result = isE(str, point);
} else {
result = false;
}
}
return result;
}
public boolean isE(char[] str, int start) {
if (str[start] != ‘e‘ && str[start] != ‘E‘) {
return false;
}
start++;
if (start == str.length) {
return false;
}
if (str[start] == ‘+‘ || str[start] == ‘-‘) {
start++;
}
if (start == str.length) {
return false;
}
while (start < str.length && str[start] <= ‘9‘ && str[start] >= ‘0‘) {
start++;
}
if (start == str.length) {
return true;
} else {
return false;
}
}
}
时间: 2024-12-29 11:14:21