【题目】
Validate if a given string is numeric.
Some examples:
"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
【解析】题意:判断一个字符串是否是计算机合法数字。
思路:把字符串分三段(小数点前、小数点与e/E之间部分、e/E之后),这三段都必须为纯数字组成的字符串。注意,第一部分和第三部分可以带符号(如+12.34e-56),第一部分和第二部分可以有一部分为空(如“.2"或"2.")。
- 去掉首尾多余的空格;
- 去掉开头的正负号;
- 看有没有e或E,如果有那么e/E后面只能是整数;
- 再看e前面的部分有没有小数点,小数点前后两部分都必须为整数。
public class Solution {
public boolean isNumber(String s) {
s = s.trim();
if (s.length() == 0) return false;
if (s.charAt(0) == '+' || s.charAt(0) == '-') {
s = s.substring(1);
}
int pose = s.indexOf("e") >= 0 ? s.indexOf("e") : s.indexOf("E");
if (pose >= 0) {
String poste = s.substring(pose + 1);
if (poste.length() == 0) return false;
if (poste.charAt(0) == '+' || poste.charAt(0) == '-') {
poste = poste.substring(1);
}
if (!isPureDigit(poste)) return false;
s = s.substring(0, pose);
}
int posdot = s.indexOf(".");
if (posdot >= 0) {
String predot = s.substring(0, posdot);
String postdot = s.substring(posdot + 1);
if (predot.isEmpty()) return isPureDigit(postdot);
if (postdot.isEmpty()) return isPureDigit(predot);
return isPureDigit(predot) && isPureDigit(postdot);
}
return isPureDigit(s);
}
public boolean isPureDigit(String s) {
if (s.isEmpty()) return false;
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) return false;
}
return true;
}
}