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’