题目
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.
答案
class Solution {
public boolean isNumber(String s) {
boolean pointSeen = false, eSeen = false, numberSeen = false, numberAfterE = false;
s = s.trim();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if('0' <= c && c <= '9') {
numberSeen = true;
numberAfterE = true;
}
else if(c == '.') {
if(pointSeen || eSeen) return false;
pointSeen = true;
}
else if(c == 'e') {
if(!numberSeen || eSeen) return false;
eSeen = true;
numberAfterE = false;
}
else if(c == '-' || c == '+') {
if(i != 0 && s.charAt(i - 1) != 'e') return false;
}
else {
return false;
}
}
return numberSeen && numberAfterE;
}
}
网友评论