[Leetcode]Valid Number

来源:互联网 发布:交易师软件 编辑:程序博客网 时间:2024/06/08 09:37

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 up front before implementing one.

判断给定的字符串是否是numeric的~题目定义的很含糊~需要自己全方面的考虑所有情况~

Example Questions Candidate Might Ask:

Q: How to account for whitespaces in the string?
A: When deciding if a string is numeric, ignore both leading and trailing whitespaces.

Q: Should I ignore spaces in between numbers– such as “1 1”?
A: No, only ignore leading and trailing whitespaces. “1 1” is not numeric.

Q: If the string contains additional characters after a number, is it considered valid?

A: No. If the string contains any non-numeric characters (excluding whitespaces and decimalpoint), it is not numeric.

Q: Is it valid if a plus or minus sign appear before the number?A: Yes. “+1” and “-1” are both numeric.

Q: Should I consider only numbers in decimal? How about numbers in other bases such ashexadecimal (0xFF)?

A: Only consider decimal numbers. “0xFF” is not numeric.

Q: Should I consider exponent such as “1e10” as numeric?
A: Yes. The OnlineJudge problem does take exponent into account.) 

Pay attention:

a single dot ‘.’ is not a valid number, but “1.”, “.1”, and“1.0” are all valid. Please note that “1.” is valid because it implies “1.0”. 

代码如下~

class Solution:    # @param s, a string    # @return a boolean    def isNumber(self, s):        if s is None or len(s) == 0: return False        i = 0        while i < len(s) and s[i] == ' ':             i += 1        if i < len(s) and (s[i] == '+' or s[i] == '-'): i += 1        isNum = False        while i < len(s) and (s[i] >= '0' and s[i] <= '9'):            isNum = True; i += 1        if i < len(s) and s[i] == '.':            i += 1            while i < len(s) and (s[i] >= '0' and s[i] <= '9'):                isNum = True; i += 1        if i < len(s) and s[i] == 'e' and isNum:            i += 1; isNum = False            if i < len(s) and (s[i] == '+' or s[i] == '-'): i += 1            while i < len(s) and (s[i] >= '0' and s[i] <= '9'):                i += 1; isNum = True        while i < len(s) and s[i] == ' ': i += 1        return isNum and (i == len(s))



0 0