Leetcode 65 Solution

This article provides solution to leetcode question 65 (valid-number)

https://leetcode.com/problems/valid-number

Solution

class Solution {
public:
    bool isNumber(string s) {
        bool num = false;
        bool numAfterExp = true;
        bool dot = false;
        bool exp = false;
        bool sign = false;
        int n = s.size();

        for (int i = 0; i < n; i++)
        {
            char ch = s[i];

            if (ch == ' ')
            {
                if (i < n - 1 && s[i + 1] != ' ' && (num || dot || exp || sign))
                    return false;
            }
            else if (ch == '+' || ch == '-')
            {
                if (i > 0 && (s[i - 1] != 'e' && s[i - 1] != ' '))
                    return false;
                sign = true;
            }
            else if ('0' <= ch && ch <= '9')
            {
                num = true;
                numAfterExp = true;
            }
            else if (ch == '.')
            {
                if (exp || dot || (i > 0 && (s[i - 1] != ' ' && s[i - 1] != '+' && s[i - 1] != '-' && !('0' <= s[i - 1] && s[i - 1] <= '9'))))
                    return false;
                dot = true;
            }
            else if (ch == 'e')
            {
                if (exp || (i == 0 || (!('0' <= s[i - 1] && s[i - 1] <= '9') && s[i - 1] != '.') || num == false))
                    return false;
                exp = true;
                numAfterExp = false;
            }
            else
                return false;
        }

        return num && numAfterExp;
    }
};