Advertisement
hoangreal

Multiply Two Strings

Oct 19th, 2024 (edited)
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.30 KB | Source Code | 0 0
  1. """
  2. Multiply Two Strings
  3. """
  4.  
  5. class Solution:
  6.     # UNRELATED TO SOLVE -- THIS IS JUST IN CASE INTERVIEWER ASKS
  7.     def multiply_number_with_single_digit(self, num: str, digit: str) -> list[str]:
  8.         from collections import deque
  9.         answers = deque([])
  10.  
  11.         remainder = 0
  12.         for i in range(len(num) - 1, -1, -1):
  13.             total = int(num[i]) * int(digit) + remainder
  14.             next_digit, remainder = total % 10, total // 10 # max = 81
  15.             answers.appendleft(str(next_digit))
  16.         # Post for processing
  17.         if remainder > 0:
  18.             answers.append_left(str(remainder))
  19.        
  20.         return answers
  21.  
  22.     def solve(self, num1: str, num2: str) -> str:
  23.         """
  24.        The idea is we compute in reversed order of num1 and num2
  25.        to get reversed order of our answer so that we can
  26.        allocate the number of zeros and distribute the remainder
  27.  
  28.        Time Complexity: O(len(num1) * len(num2))
  29.        Space Complexity: O(len(num1) + len(num2))
  30.        """
  31.  
  32.         if num1 == "0" or num2 == "0":
  33.             return "0"
  34.         answer = [0] * (len(num1) + len(num2))
  35.  
  36.         for i2 in range(len(num2) - 1, -1, -1):
  37.             digit2 = num2[i2]
  38.             # multiply 'digit2' by all digits in num1.
  39.             for i1 in range(len(num1) - 1, -1, -1):
  40.                 digit1 = num1[i1]
  41.                
  42.                 # e.g 45 * 23 = 45 * 3 * 10^0 + 45 * 3 * 10^1
  43.                 dist_from_last1 = len(num1) - 1 - i1    
  44.                 dist_from_last2 = len(num2) - 1 - i2
  45.                 num_zeros = dist_from_last1 + dist_from_last2
  46.  
  47.                 # The digit currently at position numZeros in the answer string
  48.                 # is carried over and summed with the current result.
  49.                 remainder = answer[num_zeros]
  50.                 multiplication = int(digit1) * int(digit2) + remainder
  51.                 answer[num_zeros] = multiplication % 10
  52.  
  53.                 # remainder the tens place of the multiplication result by
  54.                 # adding it to the next position in the answer array.
  55.                 answer[num_zeros + 1] += multiplication // 10
  56.  
  57.         # Pop the excess 0 from the end of answer.
  58.         if answer[-1] == 0:
  59.             answer.pop(-1)
  60.  
  61.         return "".join(str(digit) for digit in reversed(answer))
Tags: pinterest
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement