Valid Number
30%
Accepted
Validate if a given string is numeric.
Have you met this question in a real interview?
Yes
Example
"0" => true" 0.1 " => true"abc" => false"1 a" => false"2e10" => true
/**
* @param s the string that represents a number
* @return whether the string is a valid number
*/
public boolean isNumber(String s) {
// Write your code here
if(s == null || s.isEmpty()) return false;
s = s.trim();
String[] arr = s.split("e");
if(arr.length == 0 || arr.length > 2) return false;
boolean res = isValid(arr[0], false);
if(arr.length > 1){
return res && isValid(arr[1], true);
}
return res;
}
private boolean isValid(String s, boolean hasDot){
if(s.length() > 0 && (s.charAt(0) == '-' || s.charAt(0) == '+')){
s = s.substring(1);
}
if(s.length() == 0 || s.equals(".")){
return false;
}
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(c == '.'){
if(hasDot){
return false;
}
hasDot = true;
} else if(c < '0' || c > '9'){
return false;
}
}
return true;
}
}
No comments:
Post a Comment