How to multiply two strings in Python
In computer science and programming, dealing with large numbers and performing arithmetic operations on them without converting them to native data types can be a significant challenge. This is especially true when handling large datasets or working within constraints where built-in functions are unavailable or inefficient. Understanding how to manipulate numerical strings directly can provide more control and efficiency in such scenarios.
Problem statement
Calculate the product of two numbers, s1 and s2, given as strings. These numbers can be negative, and we can’t utilize any built-in function or convert the strings to integers. Zeros can appear at the beginning of numbers, and the ‘+’ sign does not need to be specified at the beginning of positive numbers.
Consider the strings "123" and "-456". They aim to compute their product, resulting in "-56088", without converting these strings to integers. Handling this problem requires string manipulation techniques to simulate multiplication as done by hand. This problem is significant in contexts where large numbers exceed typical data type limits or conversions are restricted due to specific constraints.
1 2 3× -4 5 6------------------7 3 8 (3 × -456)-6 1 5 (2 × -456, shifted one position left)-4 5 6 (1 × -456, shifted two positions left)------------------5 6 0 8 8 (sum of all intermediate products)
Sample input and output
Here is the sample input and output for the above problem:
Input
s1= "9876",s2= "-543"
Output
Product = "-5362668"
Algorithm
Consider the signs of the numbers and handle them correctly during the multiplication operation.
To calculate the product of two strings of numbers, apply the elementary school multiplication approach.
Begin multiplying each digit from the rightmost digit of one number by each digit of the other number as if we are performing manual multiplication.
Maintain a record of the intermediate products and add them together to get the final result.
Code example
def multiplyStrings(s1, s2):# Get the lengths of the input stringsm, n = len(s1), len(s2)# Detect the sign of the resultisNegative = (s1[0] == '-' and s2[0] != '-') or (s1[0] != '-' and s2[0] == '-')# Initialize the result list with zerosresult = [0] * (m + n)# Multiplication Algorithmfor i in range(m - 1, -1 + (s1[0] == '-'), -1):for j in range(n - 1, -1 + (s2[0] == '-'), -1):# Calculate the product of each digitmul = int(s1[i]) * int(s2[j]) + result[i + j + 1]result[i + j + 1] = mul % 10result[i + j] += mul // 10 # Handle carryovers# Find the position of the first non-zero digitstartpos = next((i for i, x in enumerate(result) if x != 0), m + n)if startpos == m + n:return "0"# Adjust the result based on the signif isNegative:return "-" + "".join(map(str, result[startpos:]))return "".join(map(str, result[startpos:]))# Driver code to test the functionalitys1 = "9876";s2 = "-543";# Calculate the product of two stringsproduct = multiplyStrings(s1, s2)# Display the resultprint("Python Product:", product)
Code explanation
Here’s the explanation of the above code:
Lines 1–7: This defines a function
multiplyStringsthat takes two string arguments,s1ands2. It calculates their lengthsmandn, respectively.isNegativeis a boolean that checks if the result of multiplication should be negative based on the signs ofs1ands2. Theresultis initialized as a list of zeros with a length ofm + n.Lines 10–15: This nested loop iterates through each digit of
s1ands2, starting from the least significant digit to the most significant digit. It computes the product of individual digits, considers any carryovers (mul // 10), and updates theresultlist accordingly.Lines 18–25: After computing the product,
startposfinds the index of the first non-zero digit inresult. If all digits are zero, it returns"0". Depending onisNegative, it constructs the final result string by joining the non-zero digits inresult, optionally prepending a minus sign if the result should be negative.Lines 28–35: This part demonstrates the usage of
multiplyStringswith example strings,s1ands2, computes their product using the defined function and prints the result.
Complexity analysis
Let’s understand the efficiency of the algorithm:
The method goes through the digits of the input strings once.
Constant time operations are carried out during each iteration.
Therefore, the time complexity is
, where a and b are the lengths of the input strings.
The algorithm assigns a certain amount of extra space for variables (
resultarray,isNegative,startIdx1,startIdx2, andmul.The amount of space needed is based on a few constant numbers and the length of the
resultarray.Hence, the space complexity is
for storing the result.
Free Resources