[Leetcode]Valid Number

9 篇文章 0 订阅

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))



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值