数值字符串验证问题 [英] Numeric string validation problem
问题描述
以下是问题的描述:验证给定的字符串是否为数字.
一些例子:
"0" =>真实
"0.1" =>真实
"abc" =>错误
"1个" =>错误
"2e10" =>是
到目前为止,我拥有的算法如下:
The following is a description of the problem : Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
The algorithm I have so far is the following:
public static boolean isNumber(String s) {
if(s == null){
return false;
}
s = s.toLowerCase();
s = s.trim();
if(s == "e" || s == "." || s == "/"){
return false;
}
char[] myObject = new char[]{'0','1','2','3','4','5','6','7','8','9','.','/','e'};
char[] myChar = s.toCharArray();
for (int i = 0; i < myChar.length; i++) {
int temp = 0;
while(myChar[i] != myObject[temp])
{
temp++;
if(temp == myObject.length){
return false;
}
}
}
return true;
}
当我在本地计算机上使用"e"作为输入时,它返回false,这是正确的;但是,当我在LeetCode网站上测试相同的代码时,它返回true.我不知道为什么会这样.谁能帮我吗???这是leetcode网站的副本
When I used "e" as an input in my local machine it returns false which is correct; however, when I test the same code in LeetCode website it returns true. I can not figure out why this is happening. Can anyone help me please??? Here is a copy of leetcode''s website
Input: "e"
Output: true
Expected: false
推荐答案
您的算法确实很糟糕,非常多余.此外,这是不正确的.例如,根据您的算法,某些仅包含字符"0"至"9"的字符串始终有效,但如果字符串太长,则不能为有效数字.
您需要一种完全不同的方法.只需使用您的输入字符串调用函数parseDouble
: ^ ].
从上面引用的文档中,您可以看到可以抛出NullPointerException
或NumberFormatException
.捕获它们并返回false;否则,返回false.如果未捕获到异常,则返回true.最重要的是,您可能想添加对已解析数字范围的验证.
但是,即使这段代码也将是多余的.在这种情况下,您根本不需要验证功能(除非您也验证了范围或其他内容);您最好一次执行两件事:验证并从字符串中获取数字值.如果要将其包装在将显示验证结果或返回有效数值的某些函数中,请执行此操作.
—SA
Your algorithm is really bad, very redundant. Besides, it is incorrect. According to you algorithm, for example, some strings containing only the characters ''0'' to ''9'' is always valid, but it cannot be a a valid number if it is too long.
You need a completely different approach. Simply call the functionparseDouble
with your input string: http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble%28java.lang.String%29[^].
From the documentation referenced above, you can see thatNullPointerException
orNumberFormatException
can be thrown. Catch them both and return false; if the exception wasn''t caught, return true. On top of it, you may want to add the validation for the range of the parsed number.
But even this code would be redundant. You simply don''t need a validation function in this case (unless you also validated the range or something else); you should better do two things at a time: validate and obtain the numeric value from a string. If you want to wrap it in some function which will show validation result or return a valid numeric value, do it.
—SA
这篇关于数值字符串验证问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!