字符串中数字子串的求和

题目

给定字符串s,求其中全部数字串所代表的数字之和,

  • 忽略小数点,如A1.3包含两个数字1,3
  • 紧挨着数字的字符若为’-’,出现奇数个’-'数字为负数,否则为偶数

例如,A1CD2E33,返回36

思路

记录几个变量

  • 结果 ans
  • 当前收集到的数字 num
  • 正负, positive

遍历字符串,若

  • 为数字,根据正负,改变数字num
  • 不是数字
    • 是‘-’,若前一个字符是’-'则positive=!positive,否则positive=False
    • 不是’-’,positive=True

实现

def num_sum(s):
    if s is None or len(s) == 0:
        return 0

    characters = [c for c in s]
    positive = True
    num = 0
    ans = 0

    for i in range(len(characters)):
        c = characters[i]
        n = ord(c) - ord('0')
        if n < 0 or n > 9:
            ans += num
            num = 0
            if c == '-':
                if i > 0 and characters[i-1] == '-':
                    positive = not positive
                else:
                    positive = False
            else:
                positive = True
        else:
            num = num*10 + n if positive else -n

    ans += num
    return ans

稍微改变代码结构

def num_sum2(s):
    if s is None or len(s) == 0:
        return 0

    characters = [c for c in s]
    positive = True
    num = 0
    ans = 0

    for i in range(len(characters)):
        c = characters[i]
        n = ord(c) - ord('0')
        if 0 <= n <= 9:
            num = num*10 + n if positive else -n
        else:
            if c == '-':
                prev = characters[i-1] if i > 0 else None
                positive = not positive if prev == '-' else False
            else:
                positive = True

            ans += num
            num = 0

    ans += num
    return ans

测试

def test_num_sum():
    assert(num_sum('') == 0)
    assert(num_sum('A1.3') == 4)
    assert(num_sum('A-1B') == -1)
    assert(num_sum('A--1B') == 1)
    assert(num_sum('ACD-1XX--12B') == 11)
    assert(num_sum('A-1B--2C--D6E') == 7)

    assert(num_sum2('') == 0)
    assert(num_sum2('A1.3') == 4)
    assert(num_sum2('A-1B') == -1)
    assert(num_sum2('A--1B') == 1)
    assert(num_sum2('ACD-1XX--12B') == 11)
    assert(num_sum2('A-1B--2C--D6E') == 7)


if __name__ == '__main__':
    test_num_sum()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值