Leetcode[65] Valid Number
13 Dec 2015###Task1 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.
###Java
public class Solution {
public boolean isNumber(String s) {
if (s == null || s.length() == 0) {
return false;
}
s = s.trim();
int i = 0;
int len = s.length();
if (i < len && (s.charAt(i) == '-' || s.charAt(i) == '+')) {
i++;
}
boolean isNum = false;
while (i < len && Character.isDigit(s.charAt(i))) {
i++;
isNum = true;
}
if (i < len && s.charAt(i) == '.') {
i++;
while (i < len && Character.isDigit(s.charAt(i))) {
i++;
isNum = true;
}
}
if (isNum && i < len && s.charAt(i) == 'e') {
i++;
isNum = false;
if (i < len && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
i++;
}
while (i < len && Character.isDigit(s.charAt(i))) {
i++;
isNum = true;
}
}
return isNum && i == len;
}
}
###Points
- Divide the input number into different steps:
- leading / trailing spaces
- ’+’ / ‘-‘
- Ingeter + decimal + fraction + ‘e’ + ‘+’ / ‘-‘ + integer
- One pointer problem: similar to Atoi().