Given a string s, return true if s is a valid number. Valid numbers include integers, decimals, and scientific notation (with e/E). Leading and trailing spaces are allowed. Optional signs (+/-) are allowed at the beginning or after e/E.
A valid number can have: optional sign, digits, optional decimal point with digits, optional exponent e/E with optional sign and digits. At least one digit is required in either the integer or decimal part.
This is a DFA (Deterministic Finite Automaton) problem. The key is handling all edge cases: multiple dots, multiple e's, digits required, and proper ordering of parts.
Example Input & Output
Leading/trailing spaces allowed
Not a number
Negative scientific with spaces
Scientific notation
Single zero
Algorithm Flow

Solution Approach
Best Answers
class Solution {
public boolean solution(String s) {
s=s.trim();boolean dig=false,dot=false,exp=false;
for(int i=0;i<s.length();i++){char c=s.charAt(i);
if(c>='0'&&c<='9')dig=true;
else if(c=='+'||c=='-'){if(i>0&&s.charAt(i-1)!='e'&&s.charAt(i-1)!='E')return false;}
else if(c=='.'){if(dot||exp)return false;dot=true;}
else if(c=='e'||c=='E'){if(exp||!dig)return false;exp=true;dig=false;}
else return false;
}return dig;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
