Big Integer
Big Integer, 带小数的加法。 好恶心啊!先按照小数点. 来split两部分。然后先加小数,然后把小数可能的进位丢进整数部分一起算。
class Solution(object):
def add(self, num1, num2):
if '.' in num1 and '.' in num2:
inte1, deci1 = num1.split('.')
inte2, deci2 = num2.split('.')
decimal, carry = self.doDeci(deci1, deci2)
integer = self.doInt(inte1, inte2, carry)
return '.'.join([integer, decimal])
def doDeci(self, num1, num2):
num1 = list(map(int, list(num1)))
num2 = list(map(int, list(num2)))
if len(num1)<len(num2):
num1, num2 = num2, num1
carry = 0
for i in range(len(num2)-1, -1, -1):
tmp = num2[i] + num1[i] + carry
num1[i] = tmp%10
carry = tmp//10
res = list(map(str, num1))
return ''.join(res), carry
def doInt(self, num1, num2, carry):
num1 = list(map(int,num1))[::-1]
num2 =list(map(int,num2))[::-1]
if len(num1)<len(num2):
num1, num2 = num2, num1
index = 0
while index<len(num1):
n2 = int(num2[index]) if index<len(num2) else 0
tmp = n2 + num1[index] + carry
num1[index] = tmp%10
carry = tmp//10
index += 1
if carry: num1.append(1)
num1 = list(map(str, num1))
return ''.join(num1[::-1])
num1 = '20.78'
num2 = '1.5679'
so = Solution()
ans = so.add(num1, num2)
print(ans)
不带小数的加法和乘法。
class Solution(object):
def add(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
num1 = list(num1)[::-1]
num2 = list(num2)[::-1]
if len(num1)<len(num2):
num1, num2 = num2, num1
carry = 0
index = 0
while index<len(num1):
n2 = int(num2[index]) if index<len(num2) else 0
tmp = n2 + int(num1[index]) + carry
cur = tmp%10
carry = tmp//10
num1[index] = str(cur)
index += 1
if carry: num1.append('1')
return ''.join(num1[::-1])
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
num1 = num1[::-1]
num2 = num2[::-1]
res = [0]*(len(num1) + len(num2))
for i in range(len(num2)):
for j in range(len(num1)):
tmp = int(num2[i])*int(num1[j])
res[j+i] += tmp
res[j+i+1] += res[j+i]//10
res[j+i] = res[j+i]%10
while len(res)>1 and res[-1]==0:
res.pop()
return ''.join(map(str,res))[::-1]
num1 = '124'
num2 = '5679'
so = Solution()
a = so.add(num1, num2)
print(a)
a = so.multiply(num1, num2)
print(a)