Given a string s, determine if it represents a valid number. Valid numbers include integers (123), decimals (3.14), and numbers in scientific notation (1e10, 2.5e-3). Leading and trailing spaces are allowed. Optional signs (+/-) are allowed at the beginning of the number or after the e/E in scientific notation.
For example, "0", " 3.14 ", "+100", "-5e-3", and " 2.5e+10 " are all valid. But "abc", "1a", "e3", ".", and "1..2" are not valid. An empty string or a string with only spaces is also invalid.
Validating numeric strings is a classic problem that tests your ability to handle multiple rules and edge cases simultaneously. It is commonly asked in interviews to assess systematic thinking and attention to detail. Real-world applications include parsing user input, processing CSV files, and validating configuration values.
The solution typically involves a state machine or a series of flag variables. Keep track of whether you have seen a digit, a dot, an exponent marker (e/E), and a sign. Rules: at most one dot, at most one e/E, digits must exist somewhere, and e/E requires digits after it.
Edge cases include strings with only spaces, only a sign, only a dot, multiple dots, e with no digits, and special characters. The solution must correctly reject all of these.
Example Input & Output
Leading/trailing spaces allowed
Not a number
Negative scientific with spaces
Scientific notation
Single zero
Algorithm Flow
Solution Approach
Use flag variables to track the state as you scan the string character by character.
Trim leading/trailing spaces. Track seenDigit, seenDot, and seenE flags. For each character: digits set seenDigit true; signs are only valid at position 0 or right after e/E; dots are valid only once and not after e/E; e/E is valid only once and must be preceded by a digit (then resets seenDigit for the exponent digits). Any other character returns false.
Time complexity is O(n), space complexity is O(1). This deterministic approach is cleaner than using regex or built-in parse functions, which may have platform-specific behaviors.
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.
