Valid Number LeetCode and Interviewbit solution guide

Question: Valid Number

Validate if a given string is numeric. Some examples:

"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements upfront before implementing one.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts an const char * argument, please click the reload button to reset your code definition.

Solution of Valid Number:

The major stuck point in this question is handling the corner cases. So first we need to check the below conditions to satisfy and cover all the corner scenarios. As Input is in String format.
1. Remove the spaces from the input string.
2. check if the input is a negative number.
3. check if input starts or ends with ‘e’ or ‘.’.
4. Loop through the input string and convert the string in number and count the number of decimal found
if it is more than one-time return false.
5. Also count spaces if any in-between.
6. Check if ‘e’ appears before ‘.’ then return false.

Try yourself by seeing the above hints if you are still not able to pass all the test cases then see the below solution.

//C++ Solution
class Solution {
    bool isNumber(string s) {
            return 0;
        int i=0;
        int m = s.size()-1;
        int neg = 0;
        int number = 0;
        int countdec = 0,counte = 0;
        while(s[i]==' ')i++;
        if(i==s.size()) return 0;
        while(s[m]==' ')m--;
        if(s[i]=='-' || s[i]=='+'){
            neg = 1;
        if(s[i]=='e' || s[m]=='e') return 0;
        if(i==m && s[i]=='.') return 0;
        for(int j=i;j<=m;j++){
            if((s[j]>='0' && s[j]<='9') && countdec<=1 && counte<=1){
                number = number*10 + s[j]-'0';
            }else if(s[j]==' ') return 0;
            else if(s[j]=='.' && counte==0){
                 if(s[j+1]=='e' && (j+1==m||j==i))
                    return 0;
            else if(s[j]=='e'){
                    return 0;
                if((s[j+1]=='+' || s[j+1]=='-') && j+1<m)
            else return 0;
            if(countdec>1 || counte>1) 
                return 0;
        return 1;

Python Solution:

#Python Solution
class Solution(object):
    def isNumber(self, s):
        :type s: str
        :rtype: bool
        #define DFA state transition tables
        states = [{},
                 # State (1) - initial state (scan ahead thru blanks)
                 {'blank': 1, 'sign': 2, 'digit':3, '.':4},
                 # State (2) - found sign (expect digit/dot)
                 {'digit':3, '.':4},
                 # State (3) - digit consumer (loop until non-digit)
                 {'digit':3, '.':5, 'e':6, 'blank':9},
                 # State (4) - found dot (only a digit is valid)
                 # State (5) - after dot (expect digits, e, or end of valid input)
                 {'digit':5, 'e':6, 'blank':9},
                 # State (6) - found 'e' (only a sign or digit valid)
                 {'sign':7, 'digit':8},
                 # State (7) - sign after 'e' (only digit)
                 # State (8) - digit after 'e' (expect digits or end of valid input) 
                 {'digit':8, 'blank':9},
                 # State (9) - Terminal state (fail if non-blank found)
        currentState = 1
        for c in s:
            # If char c is of a known class set it to the class name
            if c in '0123456789':
                c = 'digit'
            elif c in ' \t\n':
                c = 'blank'
            elif c in '+-':
                c = 'sign'
            # If char/class is not in our state transition table it is invalid input
            if c not in states[currentState]:
                return False
            # State transition
            currentState = states[currentState][c]
        # The only valid terminal states are end on digit, after dot, 
        # digit after e, or white space after valid input    
        if currentState not in [3,5,8,9]:
            return False
        return True

Follow us on Facebook and Twitter. For questions and queries or suggestions put them in the comment section. Read another article here.

Leave a Comment