alidate if a given string is numeric.

Have you met this question in a real interview?

Yes

Example

"0"=>true

" 0.1 "=>true

"abc"=>false

"1 a"=>false

"2e10"=>true

class Solution:
    """
    @param s: the string that represents a number
    @return: whether the string is a valid number
    """

    #a number is consist of
    #sign, int, float, 'e', sign, int

    def isNumber(self, s):
        # write your code here
        if not s or len(s) == 0:
            return False

        s = s.strip()
        if len(s) == 0:
            return False

        i = 0
        if s[i] == "+" or s[i] == "-":
            i += 1

        count_dot = 0
        count_digit = 0
        while i < len(s) and s[i] != "e":
            if s[i] == ".":
                count_dot += 1
            elif not s[i].isdigit():
                return False
            else:
                count_digit += 1
            i += 1

        if count_dot > 1 or count_digit == 0:
            return False

        if i == len(s):
            return True

        if s[i] == "e" and i == len(s) - 1:
            return False

        i += 1
        if s[i] == "+" or s[i] == "-":
            i += 1
        count_digit = 0
        while i < len(s):
            if not s[i].isdigit():
                return False
            count_digit += 1
            i += 1
        if count_digit == 0:
            return False
        return True

results matching ""

    No results matching ""