|
| 1 | +class Solution: |
| 2 | + def multiply(self, num1: str, num2: str) -> str: |
| 3 | + # If either number is "0", return "0" because the product will also be "0" |
| 4 | + if num1 == "0" or num2 == "0": |
| 5 | + return "0" |
| 6 | + |
| 7 | + # Determine the lengths of the input strings |
| 8 | + length_num1, length_num2 = len(num1), len(num2) |
| 9 | + |
| 10 | + # Create a result list to store the product digits |
| 11 | + result = [0] * (length_num1 + length_num2) |
| 12 | + |
| 13 | + # Reverse process of multiplication, processing digits from the end |
| 14 | + for i in range(length_num1 - 1, -1, -1): |
| 15 | + digit_num1 = int(num1[i]) |
| 16 | + for j in range(length_num2 - 1, -1, -1): |
| 17 | + digit_num2 = int(num2[j]) |
| 18 | + # Add product of current digits to the previously stored value in result list |
| 19 | + result[i + j + 1] += digit_num1 * digit_num2 |
| 20 | + |
| 21 | + # Handle carrying over digits > 9 to the next place |
| 22 | + for i in range(length_num1 + length_num2 - 1, 0, -1): |
| 23 | + result[i - 1] += result[i] // 10 # carry over |
| 24 | + result[i] %= 10 # keep only the last digit |
| 25 | + |
| 26 | + # Skip leading zeros in the result list |
| 27 | + start_index = 0 if result[0] != 0 else 1 |
| 28 | + |
| 29 | + # Convert the result list to string |
| 30 | + return "".join(str(digit) for digit in result[start_index:]) |
| 31 | + |
0 commit comments