Valid Number

Question

Validate if a given string is numeric.

Example

"0" => true

" 0.1 " => true

"abc" => false

"1 a" => false

"2e10" => true

Thoughts

many corner cases

  • a number can only have one dot
  • if there is a "e", the number after it should not have dot
  • starting and trailing white spaces should be removed
  • cases like "e9"
  • "+90" "-123"

if "e" exists in the string use "e" to split the string into half, then check if each half is a valid number

Solution

class Solution:
    # @param {string} s the string that represents a number
    # @return {boolean} whether the string is a valid number
    def isNumber(self, s):
        # Write your code here
        s = s.strip()
        if not s:
            return False
        if s[-1] == "e":
            return False

        arr = s.split("e")
        if len(arr) == 0 or len(arr) > 2:
            return False
        result = False
        result = self.valid(arr[0], False)
        if len(arr) == 2:
            result = result and self.valid(arr[1], True)

        return result

    def valid(self, s, hasDot):
        if len(s) == 0:
            return False
        if s[0] == "+" or s[0] == "-":
            s = s[1:]
        if s == ".":
            return False
        for i in range(len(s)):
            if s[i] == ".":
                if hasDot:
                    return False
                hasDot = True
            elif s[i] not in "0123456789":
                return False

        return True