Advertisement
hoangreal

Multiply Two Strings

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