Code Logo

Valid Number

Published at25 Jul 2026
Hard 0 views
Like0

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

Example 1
Input
" 0.1 "
Output
true
Explanation

Leading/trailing spaces allowed

Example 2
Input
"abc"
Output
false
Explanation

Not a number

Example 3
Input
" -90e3 "
Output
true
Explanation

Negative scientific with spaces

Example 4
Input
"2e10"
Output
true
Explanation

Scientific notation

Example 5
Input
"0"
Output
true
Explanation

Single zero

Algorithm Flow

Recommendation Algorithm Flow for Valid Number
Recommendation Algorithm Flow for Valid Number

Solution Approach

function solution(s) {
  s = s.trim();
  var seenDigit = false, seenDot = false, seenE = false;
  for (var i = 0; i < s.length; i++) {
    var c = s.charAt(i);
    if (c >= '0' && c <= '9') { seenDigit = true; }
    else if (c === '+' || c === '-') {
      if (i > 0 && s.charAt(i-1) !== 'e' && s.charAt(i-1) !== 'E') return false;
    }
    else if (c === '.') {
      if (seenDot || seenE) return false;
      seenDot = true;
    }
    else if (c === 'e' || c === 'E') {
      if (seenE || !seenDigit) return false;
      seenE = true;
      seenDigit = false;
    }
    else return false;
  }
  return seenDigit;
}

Best Answers

java
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;
    }
}