codewars——String incrementer(新get了zfill方法的使用)

Your job is to write a function which increments a string, to create a new string.
If the string already ends with a number, the number should be incremented by 1.
If the string does not end with a number. the number 1 should be appended to the new string.

Examples:
foo -> foo1
foobar23 -> foobar24
foo0042 -> foo0043
foo9 -> foo10
foo099 -> foo100
Attention: If the number has leading zeros the amount of digits should be considered.

思路

按我的笨办法,这个题依旧是暴力遍历易于理解,那么就是两个思路,反向遍历还是正向遍历。

我选择反向遍历

py的for循环很简单,但是这里,我用c语言的for循环模式来写代码(注意是模式不是格式),我用下标来控制循环,这样更方便更该数值。
反向遍历更能快速找出字符串最后的舒总

关键asc码

ord(‘0’)=48
rod(‘9’)=57

代码

def increment_string(string):
    key = -1
    num = ''
    for i in range(len(string) - 1, -1, -1):
        if ord(string[i]) < 48 or ord(string[i]) > 57:
            key = i
            break
        num += string[i]
    if key == len(string) - 1:
        return string + '1'       
    if key != -1:
        finallyNum = num[-1::-1]
        length = len(finallyNum)
        resultNum = str(int(finallyNum) + 1).zfill(length)
        result = string[0:key+1] + resultNum
        return result
    else:
        length = len(string)
        result = str(int(string) + 1).zfill(length)
        return result

今日收获

zfill方法,返回其参数相同位数的数字,不足位的用0补在前面
例如:

x = '3'
x.zfill(5)

输出结果为’00005’

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值