Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def add(self, num1, num2):
- if not num1 or not num2:
- return num1 or num2
- if num1 == '0':
- return num2
- if num2 == '0':
- return num1
- long = num1 if len(num1) >= len(num2) else num2
- short = num1 if len(num1) < len(num2) else num2
- diff = len(long) - len(short)
- long1 = long[:diff]
- long2 = long[diff:]
- res = ''
- carry = 0
- i = len(short) - 1
- while i >= 0:
- num1 = ord(short[i]) - ord('0')
- num2 = ord(long2[i]) - ord('0')
- temp = num1 + num2 + carry
- d = chr(temp % 10 + ord('0'))
- carry = temp // 10
- res = d + res
- i = i - 1
- i = len(long1) - 1
- while i >= 0:
- num = ord(long1[i]) - ord('0')
- temp = num + carry
- d = chr(temp % 10 + ord('0'))
- carry = temp // 10
- res = d + res
- i = i - 1
- if carry:
- d = chr(carry + ord('0'))
- res = d + res
- return res
- def multiply(self, num1, num2):
- """
- :type num1: str
- :type num2: str
- :rtype: str
- """
- if num1 is '0' or num2 is '0':
- return '0'
- if not num1 or not num2:
- return '0'
- long = num1 if len(num1) >= len(num2) else num2
- short = num1 if len(num1) < len(num2) else num2
- res = ''
- zero = 0
- i = len(short) - 1
- while i >= 0:
- carry = 0
- num1 = ord(short[i]) - ord('0')
- res_t = '0' * zero
- j = len(long) - 1
- while j >= 0:
- num2 = ord(long[j]) - ord('0')
- temp = num1 * num2 + carry
- carry = temp // 10
- p = chr(temp % 10 + ord('0'))
- res_t = p + res_t
- j = j - 1
- if carry:
- p = chr(carry + ord('0'))
- res_t = p + res_t
- res = self.add(res, res_t)
- zero = zero + 1
- i = i - 1
- return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement