题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串”+100”,”5e2”,”-123”,”3.1416”和”-1E-16”都表示数值。 但是”12e”,”1a3.14”,”1.2.3”,”+-5”和”12e+4.3”都不是。 地址:牛客链接
问题分析
代码实现
public class Solution {
public boolean isNumeric(char [] str ) {
if (str == null || str .length == 0 ) {
return false ;
}
if (str .length == 1 && (str [0 ] < '0' || str [0 ] > '9' )) {
return false ;
}
char preValue = ' ' ;
if (str [0 ] == '+' || str [0 ] == '-' || (str [0 ] >= '0' && str [0 ] <= '9' )) {
preValue = str [0 ];
}else if (str [0 ] == '.' ){
return afterDot(str , 1 );
}else {
return false ;
}
for (int i = 1 ; i < str .length; i++) {
char ch = str [i];
if (ch >= '0' && ch <= '9' ) {
preValue = ch;
}else if (ch == '.' && ((preValue >= '0' && preValue <= '9' ) || preValue == '-' || preValue == '+' )) {
return afterDot(str , i+1 );
}else if (ch == 'e' || ch == 'E' && (preValue >= '0' && preValue <= '9' )) {
return afterE(str , i+1 );
}else {
return false ;
}
}
return true ;
}
public boolean afterDot(char [] str , int begin) {
if (str [begin] < '0' || str [begin] > '9' ) {
return false ;
}
for (int i = begin + 1 ; i < str .length; i++) {
if (str [i] == 'e' || str [i] == 'E' ) {
return afterE(str , i+1 );
}
if (str [i] < '0' || str [i] > '9' ) {
return false ;
}
}
return true ;
}
public boolean afterE(char [] str , int begin) {
if (begin >= str .length) {
return false ;
}
if (str [begin] != '+' && str [begin] != '-' && (str [begin] < '0' && str [begin] > '9' )) {
return false ;
}
for (int i = begin + 1 ; i < str .length; i++) {
if (str [i] < '0' || str [i] > '9' ) {
return false ;
}
}
return true ;
}
}