Read in two numbers in the form of a string, write a function to calculate their sum, and return it in the form of a string.
(The length of the string is not greater than 100000, and it is guaranteed that the string is only composed of 10 characters from '0' to '9')
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
# 计算两个数之和
# @param s string字符串 表示第一个整数
# @param t string字符串 表示第二个整数
# @return string字符串
#
class Solution:
def solve(self , s , t ):
maxlen = len(s)
if maxlen < len(t):
maxlen = len(t)
s = s.zfill(maxlen)
t = t.zfill(maxlen)
shiwei = 0
sum = ''
for i in range(-1,-maxlen-1,-1):
temp= ord(s[i]) +ord(t[i]) - 96 + shiwei
if temp >= 10:
shiwei = 1
temp = temp - 10
else:
shiwei=0
sum+=str(temp)
if shiwei != 0:
sum+=str(shiwei)
return sum[::-1]
Main key points
- zfill function use: right-aligned fill
- range(-1,-maxlen-1,-1): meaning, starting from the last bit
- The meaning of ord(s[i]) function; convert the string into ASCII code corresponding number, if it is a pure number, -48 is required
- [::-1] Meaning: output the string in reverse.
test:
s="733064366"
t="459309139"
print(s)
print(t)
maxlen = len(s)
if maxlen < len(t):
maxlen = len(t)
s = s.zfill(maxlen)
t = t.zfill(maxlen)
print(s)
print(t)
# print(maxlen)
shiwei = 0
sum = ''
for i in range(-1,-maxlen-1,-1):
#print(i)
temp= ord(s[i]) +ord(t[i]) - 96 + shiwei
if temp >= 10:
shiwei = 1
temp = temp - 10
else:
shiwei=0
sum+=str(temp)
if shiwei != 0:
sum+=str(shiwei)
print(sum[::-1])