Add Strings
程序员文章站
2022-06-04 10:58:59
...
Add Strings
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
Solution
class Solution:
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
list_num = [0]*(max(len(num1), len(num2))+1)
num1 = num1[::-1]
num2 = num2[::-1]
ret = ''
carry = 0
for i in range(max(len(num1), len(num2))+1):
a = int(num1[i]) if i<len(num1) else 0
b = int(num2[i]) if i<len(num2) else 0
digit = (a+b+carry)%10
carry = (a+b+carry)//10
list_num[i] = digit
list_num.reverse()
for num in list_num:
ret += str(num)
if ret[0]=='0':
ret = ret[1::]
return ret
上一篇: Add Binary
下一篇: PostGIS数据库中的几种复杂查询举例
推荐阅读
-
ALTER TABLE ADD 增加多个字段 外键约束
-
WebService提供Add和getStudent服务(IIS发布)
-
43-Android之提取所有的strings.xml文件
-
Java基础学习总结(129)——Arrays.asList得到的List进行add和remove等操作出现异常解析
-
Java中List add添加不同类型元素的讲解
-
MySQL添加外键时报错:1215 Cannot add the foreign key constraint的解决方法
-
解决Eclipse add external jars运行出现java.lang.NoClassDefFoundError的方法
-
MySQL的Data_ADD函数与日期格式化函数说明
-
C#实现去除Strings中空格的方法
-
MySQL添加外键时报错:1215 Cannot add the foreign key constraint的解决方法