我在最近几个小时内一直在努力解决这个问题,而且我自己也无法找到解决方案。问题很简单:
In: 'subtract('1.1.5', 4)'
Out: '1.1.1'
In: 'subtract('1.1.5', 6)'
Out: '1.0.9'
In: 'subtract('1.0.0', 1)'
Out: '0.9.9'
In: 'subtract('1.14.5', 8)'
Out: '1.13.7'
In: 'subtract('1.10.10', 20)'
Out: '1.9.0'
我提出了一些非常复杂的复杂算法,这些算法似乎很容易解决,有什么想法吗?
这是我迄今为止所尝试的(不适用于所有情况):
def subtract(version, sub):
arrV = version.split('.')
index = len(arrV) - 1
sub = -abs(sub)
while(sub < 0 and index >= 0):
vLen = len(arrV[index])
m = 10 ** (vLen - 1)
i = int(arrV[index])
if (i + sub < 0):
arrV[index] = str(m - (abs(sub) % m))
sub = int(sub / m)
else:
arrV[index] = str(i + sub)
sub = 0
index -= 1
print(arrV)
return '.'.join(arrV)
print(subtract('1.10.10', 5) == '1.10.5')
print(subtract('1.10.10', 12) == '1.9.8')
print(subtract('1.10.10', 10) == '1.10.0')
print(subtract('1.10.10', 1010) == '1.0.0')