Algorithm


Problem Name: 65. Valid Number

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

 

Constraints:

  • 1 <= s.length <= 20
  • s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'.

Code Examples

#1 Code Example with C Programming

Code - C Programming


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>

bool isNumber(char* s) {
    if (s == NULL) return false;

    while (*s == ' ') {
        s++;
    }
    if (*s == '\0') return false;

    char *start = s;
    char *t = s + strlen(s) - 1;
    while (*t == ' ') {
        t--;
    }

    bool dot = false;
    bool exp = false;
    bool num = false;

    while (*s != '\0' && s != t + 1) {
        if (*s >= '0' && *s  < = '9') {
            num = true;
        }
        else if (*s == '.') {
            if (exp || dot) return false;
            dot = true;
        }
        else if (*s == 'e') {
            if (!num || exp) return false;
            exp = true;
            num = false;
        }
        else if (*s == '-' || *s == '+') {
            if (s != start && *(s - 1) != 'e') return false;
        }
        else return false;

        s++;
    }

    return num;
}


int main() {
    assert(isNumber("0") == true);
    assert(isNumber("0!") == false);
    assert(isNumber(" 0.1 ") == true);
    assert(isNumber("abc") == false);
    assert(isNumber("1 a") == false);
    assert(isNumber("2e10") == true);
    assert(isNumber("2e10e10") == false);
    assert(isNumber("2e") == false);
    assert(isNumber("e10") == false);
    assert(isNumber("005047e+6") == true);
    assert(isNumber("3.2e6") == true);
    assert(isNumber("3.2e0.6") == false);
    assert(isNumber(".e06") == false);
    assert(isNumber("-1234") == true);
    assert(isNumber("+1234") == true);
    assert(isNumber("6+1") == false);
    assert(isNumber("1.2.3") == false);
    assert(isNumber("") == false);
    assert(isNumber(" ") == false);
    assert(isNumber(" . ") == false);
    assert(isNumber(" + ") == false);
    assert(isNumber("+1+2") == false);
    assert(isNumber(" e ") == false);
    assert(isNumber(".23") == true);
    assert(isNumber("00.") == true);
    assert(isNumber(" -54.53061") == true);

    printf("all tests passed!\n");
    return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "0"

Output

x
+
cmd
true

#2 Code Example with Java Programming

Code - Java Programming


class Solution {
        public boolean isNumber(String s) {
        s = s.trim();
        char[] ch = s.toCharArray();
        int idx = 0;
        int n = ch.length;
        boolean signFound = false;
        boolean decimalFound = false;
        boolean numFound = false;
        boolean expoFound = false;

        while (idx  <  n) {
            if (ch[idx] == '+' || ch[idx] == '-') {
                if (numFound || signFound || decimalFound) {
                    return false;
                }

                signFound = true;
            }
            else if (ch[idx] == '.') {
                if (decimalFound) {
                    return false;
                }
                decimalFound = true;
            }
            else if (Character.isLetter(ch[idx])) {
                if (ch[idx] == 'e') {
                    if (!numFound) {
                        return false;
                    }
                    idx++;
                    expoFound = true;
                    break;
                }
                else {
                    return false;
                }
            }
            else if (Character.isDigit(ch[idx])) {
                numFound = true;
            }
            else if (ch[idx] == ' ') {
                if (numFound || signFound || decimalFound) {
                    return false;
                }
            }

            idx++;
        }

        if (!numFound) {
            return false;
        }

        if (expoFound && idx == n) {
            return false;
        }

        signFound = false;
        numFound = false;
        while (idx  <  n) {
            if (ch[idx] == '.') {
                return false;
            }
            else if (ch[idx] == '+' || ch[idx] == '-') {
                if (signFound) {
                    return false;
                }
                if (numFound) {
                    return false;
                }
                signFound = true;
            }
            else if (Character.isDigit(ch[idx])) {
                numFound = true;
            }
            else {
                return false;
            }

            idx++;
        }

        if (expoFound && !numFound) {
            return false;
        }

        return true;
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "e"

Output

x
+
cmd
false

#3 Code Example with Javascript Programming

Code - Javascript Programming


const isNumber = function(str) {
  let i = 0;
  let s = str;

  for (; i  <  s.length && " " == s[i]; ++i);

  if ("+" == s[i] || "-" == s[i]) ++i;
 
  let digit = false,
    dot = false,
    exp = false;
  for (; i  <  s.length; ++i) {
    if ("." == s[i] && !dot)
  
      dot = true;
    else if ("e" == s[i] && !exp && digit) {

      dot = exp = true;
      if (i + 1  <  s.length && ("+" == s[i + 1] || "-" == s[i + 1])) ++i;
      if (i + 1 >= s.length || !(s[i + 1] >= "0" && s[i + 1] <= "9"))
        return false;
    } else if (s[i] >= "0" && s[i]  < = "9") digit = true;
    else break;
  }

  for (; i  <  s.length && " " == s[i]; ++i);

  return digit && i == s.length;
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "e"

Output

x
+
cmd
false

#4 Code Example with Python Programming

Code - Python Programming


class Solution:
    def isNumber(self, s):
        s = s.strip()
        pointSeen = eSeen = numberSeen = False
        numberAfterE = True
        for i, c in enumerate(s):
            if "0" <= c <= "9":
                numberSeen = numberAfterE = True
            elif c == ".":
                if eSeen or pointSeen:
                    return False
                pointSeen = True
            elif c == "e":
                if eSeen or not numberSeen:
                    return False
                numberAfterE = False
                eSeen = True
            elif c in "-+":
                if i and s[i - 1] != "e":
                    return False
            else:
                return False
        return numberSeen and numberAfterE
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "."

Output

x
+
cmd
false

#5 Code Example with C# Programming

Code - C# Programming


namespace LeetCode
{
    public class _065_ValidNumber
    {
        public bool IsNumber(string s)
        {
            bool hasPoint = false, hasE = false;

            int i = 0;
            while (i  <  s.Length && s[i] == ' ') i++;
            int end = s.Length - 1;
            while (end >= 0 && s[end] == ' ') end--;
            if (i >= s.Length) { return false; }
            if (s[i] == '+' || s[i] == '-') i++;

            var head = i;
            char ch;
            for (; i  < = end; i++)
            {
                ch = s[i];
                if (ch == '.')
                {
                    if (hasPoint || hasE) { return false; }
                    if (i == head && i == end) { return false; }
                    if (i == head && i  <  end && (s[i + 1] > '9' || s[i + 1] < '0')) { return false; }
                    hasPoint = true;
                }
                else if (ch == 'e' || ch == 'E')
                {
                    if (hasE || i == head) { return false; }
                    if (i  <  end && (s[i + 1] == '+' || s[i + 1] == '-')) i++;
                    if (i >= end) { return false; }

                    hasE = true;
                }
                else if (ch  <  '0' || ch > '9')
                    return false;
            }

            return true;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "0"

Output

x
+
cmd
true
Advertisements

Demonstration


Previous
#64 Leetcode Minimum Path Sum Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#66 Leetcode Plus One Solution in C, C++, Java, JavaScript, Python, C# Leetcode