Valid Number LeetCode Solution

Last updated on March 2nd, 2025 at 03:56 pm

Here, we see a Valid Number LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Math, String

Companies

LinkedIn

Level of Question

Hard

Valid Number LeetCode Solution

Valid Number LeetCode Solution

1. Problem Statement

A valid number can be split up into these components (in order):

  1. A decimal number or an integer.
  2. (Optional) An 'e' or 'E', followed by an integer.

A decimal number can be split up into these components (in order):

  1. (Optional) A sign character (either '+' or '-').
  2. One of the following formats:
    1. One or more digits, followed by a dot '.'.
    2. One or more digits, followed by a dot '.', followed by one or more digits.
    3. A dot '.', followed by one or more digits.

An integer can be split up into these components (in order):

  1. (Optional) A sign character (either '+' or '-').
  2. One or more digits.

For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"].

Given a string s, return true if s is a valid number.

Example 1:

Input: s = "0"
Output: true

Example 2:

Input: s = "e"
Output: false

Example 3:

Input: s = "."
Output: false

2. Coding Pattern Used in Solution

The provided code follows a “State Machine” pattern. This pattern is used to validate the input string by transitioning through different states based on the characters encountered. The code uses boolean flags (digitSeendotSeeneSeen, etc.) to track the state of the string as it is parsed, ensuring that the string adheres to the rules of a valid number.

3. Code Implementation in Different Languages

3.1 Valid Number C++

class Solution {
public:
    bool isNumber(string s) {
        bool digitSeen=false, dotSeen=false, eSeen=false;
        int plusMinus=0,n=s.length();
        for(int i=0; i<n; i++)
        {
            if(s[i]-'0'>=0 && s[i]-'0'<=9)
                digitSeen=true;
            else if(s[i]=='+' || s[i]=='-')
            {
                if(plusMinus==2 || (i>0 && (s[i-1]!='e' && s[i-1]!='E')) || i==n-1) return false;
                plusMinus++;
            }
            else if(s[i]=='e' || s[i]=='E')
            {
                if(eSeen || !digitSeen || i==n-1) return false;
                eSeen=true;
            }
            else if(s[i]=='.')
            {
                if(eSeen || dotSeen || (i==n-1 && !digitSeen)) return false;
                dotSeen=true;
            }
            else
              return false;
        }
        return true;        
    }
};

3.2 Valid Number Java

class Solution {
    public boolean isNumber(String s) {
        boolean num = false, exp = false, sign = false, dec = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') num = true ;    
            else if (c == 'e' || c == 'E')
                if (exp || !num) return false;
                else {
                    exp = true;
                    sign = false;
                    num = false;
                    dec = false;
                }
            else if (c == '+' || c == '-')
                if (sign || num || dec) return false;
                else sign = true;
            else if (c == '.')
                if (dec || exp) return false;
                else dec = true;
            else return false;
        }
        return num;        
    }
}

3.3 Valid Number JavaScript

var isNumber = function(s) {
    let exp = false, sign = false, num = false, dec = false
    for (let c of s)
        if (c >= '0' && c <= '9') num = true     
        else if (c === 'e' || c === 'E')
            if (exp || !num) return false
            else exp = true, sign = false, num = false, dec = false
        else if (c === '+' || c === '-')
            if (sign || num || dec) return false
            else sign = true
        else if (c === '.')
            if (dec || exp) return false
            else dec = true
        else return false
    return num    
};

3.4 Valid Number Python

class Solution(object):
    def isNumber(self, s):
        try:
            if 'inf' in s.lower() or s.isalpha():
                return False
            if float(s) or float(s) >= 0:
                return True
        except:
            return False

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n)O(1)
JavaO(n)O(1)
JavaScriptO(n)O(1)
PythonO(n)O(1)

Scroll to Top