【发布时间】:2023-01-08 00:04:27
【问题描述】:
我正在尝试解决来自 Codewars 的 this 练习。
描述:
给定两个整数的字符串表示形式,返回这些整数之和的字符串表示形式。 例如:sumStrings('1','2') // => '3' 除了十个数字“0”到“9”之外,整数的字符串表示将不包含任何字符。 我已经删除了 BigInteger 和 BigDecimal 在 java 中的使用 Python:您的解决方案需要处理大量数字(大约一百万位数),转换为 int 将不起作用。
在 Python 中,我所有的测试用例都正常,但执行超时仍然出现。有什么提示可以让它工作吗?我还可以采用什么其他方法? 我当前的代码在下面。 非常感谢任何帮助!
def sum_strings(x, y):
if x == '' and y == '':
return '0'
if x == '0' and y == '0':
return '0'
if x == '' and y == '0' or x == '0' and y == '':
return '0'
listaX = list(x)
listaY = list(y)
if len(listaX) - len(listaY) > 0:
while len(listaY) < len(listaX):
listaY.insert(0, '0')
if len(listaY) - len(listaX) > 0:
while len(listaY) > len(listaX):
listaX.insert(0, '0')
for i in range(0, len(listaX)):
listaX[i] = int(listaX[i])
listaY[i] = int(listaY[i])
listaSomas = []
quociente = 0
for i in range(len(listaX) - 1, -1, -1):
soma = listaX[i] + listaY[i] + quociente
if soma > 9 and i > 0:
quociente = soma // 10
listaSomas.insert(0, soma % 10)
elif soma > 9 and i == 0:
quociente = soma // 10
listaSomas.insert(0, soma % 10)
listaSomas.insert(0, quociente)
elif soma <= 9:
listaSomas.insert(0, soma)
quociente = 0
if listaSomas[0] == 0:
listaSomas.remove(listaSomas[0])
for i in range(0, len(listaSomas)):
listaSomas[i] = str(listaSomas[i])
listaSomas = ''.join(listaSomas)
return listaSomas
#MAIN
print(sum_strings('123', '456'))
【问题讨论】:
-
复制到不同的容器。在前面插入,转换为不同的类型。这些可能是对一个非常大的字符串进行的昂贵操作。您可以使用 reversed 来获取迭代器,将它们与 itertools.zip_longest(fillvalue='0') 结合使用以对单个数字进行基本算术运算,然后再次将其反转以进行输出吗?