Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Multiply Two Strings
- """
- class Solution:
- # UNRELATED TO SOLVE -- THIS IS JUST IN CASE INTERVIEWER ASKS
- def multiply_number_with_single_digit(self, num: str, digit: str) -> list[str]:
- from collections import deque
- answers = deque([])
- remainder = 0
- for i in range(len(num) - 1, -1, -1):
- total = int(num[i]) * int(digit) + remainder
- next_digit, remainder = total % 10, total // 10 # max = 81
- answers.appendleft(str(next_digit))
- # Post for processing
- if remainder > 0:
- answers.append_left(str(remainder))
- return answers
- def solve(self, num1: str, num2: str) -> str:
- """
- The idea is we compute in reversed order of num1 and num2
- to get reversed order of our answer so that we can
- allocate the number of zeros and distribute the remainder
- Time Complexity: O(len(num1) * len(num2))
- Space Complexity: O(len(num1) + len(num2))
- """
- if num1 == "0" or num2 == "0":
- return "0"
- answer = [0] * (len(num1) + len(num2))
- for i2 in range(len(num2) - 1, -1, -1):
- digit2 = num2[i2]
- # multiply 'digit2' by all digits in num1.
- for i1 in range(len(num1) - 1, -1, -1):
- digit1 = num1[i1]
- # e.g 45 * 23 = 45 * 3 * 10^0 + 45 * 3 * 10^1
- dist_from_last1 = len(num1) - 1 - i1
- dist_from_last2 = len(num2) - 1 - i2
- num_zeros = dist_from_last1 + dist_from_last2
- # The digit currently at position numZeros in the answer string
- # is carried over and summed with the current result.
- remainder = answer[num_zeros]
- multiplication = int(digit1) * int(digit2) + remainder
- answer[num_zeros] = multiplication % 10
- # remainder the tens place of the multiplication result by
- # adding it to the next position in the answer array.
- answer[num_zeros + 1] += multiplication // 10
- # Pop the excess 0 from the end of answer.
- if answer[-1] == 0:
- answer.pop(-1)
- return "".join(str(digit) for digit in reversed(answer))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement