Valid Number
Hard
Topics
Given a string s, return true if s is a valid number. A valid number has an optional sign, an integer or decimal part with at least one digit, and an optional exponent (e or E) followed by an optional sign and at least one digit.
Example 1
Input: s = "0" Output: true
Example 2
Input: s = "e" Output: false
Example 3
Input: s = "-90E3" Output: true
Constraints
- 1 <= s.length <= 12
- s consists of digits, '+', '-', '.', 'e', 'E'.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The grammar is small enough to parse in one left-to-right pass, and writing it as a scan rather than a pile of conditionals is what keeps it correct: an optional sign, then a mantissa, then an optional exponent, then end of input.
The mantissa rule is the one people get wrong. It needs at least one digit and at most one dot, and the digit may be on either side of the dot — so "3." and ".8" are both valid while "." is not. The scan handles this by consuming digits and dots together, counting each, and then checking the digit count once at the end.
The exponent, if present, has its own optional sign and requires at least one digit — it may not contain a dot. The final i == n test is what rejects trailing junk and makes the whole thing airtight.
Approach
- Consume an optional leading sign.
- Consume digits and dots, counting both; reject on a second dot.
- Reject if no digit was seen.
- If
eorEfollows, consume an optional sign and then digits, rejecting if there are none. - Accept only if the whole string was consumed.
Dry Run
verified against a regex reference on all 54,240 strings of length up to 4
over the alphabet 0-9 + - . e E -- every verdict agrees
"0" true
"2e10" true
"-90E3" true
"53.5e93" true
"+6e-1" true
"3." true a digit before the dot is enough
"+.8" true a digit after the dot is enough
"e" false no mantissa
"." false a dot with no digit
" 1" false leading space is not in the grammar
"1e" false exponent with no digits
"99e2.5" false the exponent may not contain a dot
"--6" false only one sign
"-+3" false
"95a54e53" false stray letter, caught by the final i == n test
".e1" false no mantissa digitComplexity
- Time — O(n): each character is examined once; the scan never backtracks.
- Space — O(1): a position and three counters.
- A regular expression expresses the same grammar in one line and is the right answer in production. The hand scan is what the problem is testing, and it is also what you would write if the grammar needed extending.
Common Pitfalls
- Accepting
"."on its own. The dot is optional punctuation; the digit is mandatory. - Rejecting
"3."or".8". Both are valid — the digit may sit on either side. - Allowing a dot inside the exponent.
"99e2.5"is invalid, which a shared digit-and-dot loop would wrongly accept if reused for the exponent. - Allowing more than one sign, or a sign anywhere other than at the very start or immediately after
e. - Forgetting the final
i == ncheck, which is the only thing rejecting trailing characters like the"a"in"95a54e53". - Trimming whitespace. This statement's alphabet contains no space, so a leading or trailing space is simply invalid — trimming would silently accept it.
- Trying to enumerate states by hand with nested conditionals. It is doable and it is where the off-by-one cases hide; the linear scan with explicit counters is easier to argue about.
Full Solution — all languages
class Solution:
def isNumber(self, s):
i = 0
n = len(s)
if n == 0:
return False
if s[i] == '+' or s[i] == '-':
i += 1
digits = 0
dots = 0
while i < n and (s[i].isdigit() or s[i] == '.'):
if s[i] == '.':
dots += 1
if dots > 1:
return False
else:
digits += 1
i += 1
if digits == 0:
return False
if i < n and (s[i] == 'e' or s[i] == 'E'):
i += 1
if i < n and (s[i] == '+' or s[i] == '-'):
i += 1
ed = 0
while i < n and s[i].isdigit():
ed += 1
i += 1
if ed == 0:
return False
return i == nimport java.util.*;
class Solution {
public boolean isNumber(String s) {
int i = 0, n = s.length();
if (n == 0) return false;
if (s.charAt(i) == '+' || s.charAt(i) == '-') i++;
int digits = 0, dots = 0;
while (i < n && ((s.charAt(i) >= '0' && s.charAt(i) <= '9') || s.charAt(i) == '.')) {
if (s.charAt(i) == '.') {
dots++;
if (dots > 1) return false;
} else digits++;
i++;
}
if (digits == 0) return false;
if (i < n && (s.charAt(i) == 'e' || s.charAt(i) == 'E')) {
i++;
if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) i++;
int ed = 0;
while (i < n && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
ed++;
i++;
}
if (ed == 0) return false;
}
return i == n;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isNumber(string s) {
int i = 0, n = s.size();
if (n == 0) return false;
if (s[i] == '+' || s[i] == '-') i++;
int digits = 0, dots = 0;
while (i < n && ((s[i] >= '0' && s[i] <= '9') || s[i] == '.')) {
if (s[i] == '.') {
dots++;
if (dots > 1) return false;
} else digits++;
i++;
}
if (digits == 0) return false;
if (i < n && (s[i] == 'e' || s[i] == 'E')) {
i++;
if (i < n && (s[i] == '+' || s[i] == '-')) i++;
int ed = 0;
while (i < n && s[i] >= '0' && s[i] <= '9') {
ed++;
i++;
}
if (ed == 0) return false;
}
return i == n;
}
};/**
* @param {string} s
* @return {boolean}
*/ var isNumber = function(s) {
let i = 0;
const n = s.length;
if (n === 0) return false;
if (s[i] === '+' || s[i] === '-') i++;
let digits = 0, dots = 0;
while (i < n && ((s[i] >= '0' && s[i] <= '9') || s[i] === '.')) {
if (s[i] === '.') {
dots++;
if (dots > 1) return false;
} else digits++;
i++;
}
if (digits === 0) return false;
if (i < n && (s[i] === 'e' || s[i] === 'E')) {
i++;
if (i < n && (s[i] === '+' || s[i] === '-')) i++;
let ed = 0;
while (i < n && s[i] >= '0' && s[i] <= '9') {
ed++;
i++;
}
if (ed === 0) return false;
}
return i === n;
};