题目
给定一个字符串s,编写一个方法(函数),如果它有一个有效的单个整数或浮点数,将返回true,否则返回false。
有效的例子应该返回true:
isDigit("3")
isDigit(" 3 ")
isDigit("-3.23")
应该返回false:
isDigit("3-4")
isDigit(" 3 5")
isDigit("3 5")
isDigit("zero")
测试用例:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class DigitTest {
MyUtilities myUtil = new MyUtilities();
@Test
public void test0() throws Exception
{
assertEquals(false,myUtil.isDigit("s2324"));
}
@Test
public void test1() throws Exception
{
assertEquals(true,myUtil.isDigit("-234.4"));
}
}
解题
我的:
这题搞了我一天,最后还是借助了网友的力量,一开始我也设想过正则,但是一直写不出最完善的正则表达式,最终作罢。
public boolean isDigit(String s) {
char[] arrs = s.toCharArray();
boolean flag = false;
for (int i = 0, point = 0, nume1 = 0, nume2 = 0; i < arrs.length; i++) {
flag = true;
//如果数字中出现其他字符,为NO。
if ((arrs[i] < 48 || arrs[i] > 57) && arrs[i] != '.' && arrs[i] != 'E' && arrs[i] != '-') {
flag = false;
break;
}
if (arrs[i] == 'E') {
nume1++;
//如果'E'出现在第一个和最后一个,为NO
if (i + 1 == arrs.length || i == 0) {
flag = false;
break;
}
} else if (arrs[i] == '.') {
point++;
//如果'.'出现在第一个或者最后一个,或者出现在'E'之后,为NO
if (i + 1 == arrs.length || i == 0 || nume1 > 0) {
flag = false;
break;
}
} else if (arrs[i] == '-') {
nume2++;
//如果'-'出现在第一个为yes,但'-'没有紧挨着在'E'之后,为NO
if (i == 0) {
break;
} else if (arrs[i - 1] != 'E') {
flag = false;
break;
}
}
//如果'E','.','-'出现的次数多于一个,为NO
if (nume1 > 1 || nume2 > 1 || point > 1) {
flag = false;
break;
}
}
return flag;
}
别人的:
1、正则表达式法
public class MyUtilities{
private static final String NUMBER_REGEX =
"\\s*" // any amount of whitespace
+ "-?" // optional negative sign
+ "\\d+" // one or more digits
+ "(:?" // start of factional part
+ "\\." // literal period
+ "\\d+" // one or more digits
+ ")?" // fractional part is optional
+ "\\s*"; // any amount of whitespace
public boolean isDigit(String s)
{
return s.matches(NUMBER_REGEX);
}
}
public class MyUtilities{
public boolean isDigit(String s)
{
return s.matches("[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)");
}
}
2、取巧低效法,实际不会将异常用作控制流
public class MyUtilities{
public boolean isDigit(String s)
{
try
{
Double.parseDouble(s);
return true;
}catch(Exception e)
{
return false;
}
}
}
思考
这道题始终没有领会出题者的意图。饶了很多弯,真是绞尽脑汁,而且正则不够精通。