无聊的刷题笔记

Add Strings

LeetCode 415

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.

class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
ans = ''
carry = 0
i = 0
if len(num1)>len(num2):
num1, num2 = num2, num1
while i<len(num1):
a = ord(num1[len(num1)-1-i]) - ord('0')
b = ord(num2[len(num2)-1-i]) - ord('0')
r = a + b + carry
carry = r/10
ans = chr(r%10+ord('0')) + ans
i+=1
while carry and i<len(num2):
b = ord(num2[len(num2)-1-i]) - ord('0')
r = b + carry
carry = r/10
ans = chr(r%10+ord('0')) + ans
i+=1
if carry:
ans = '1' + ans
else:
ans = num2[0:len(num2)-i] + ans
return ans