24. Multiply two strings
The problem can be found at the following link: Question Link
My Approach
I've implemented multiplication of two strings by simulating the process as we manually does, similar to how we do long multiplication by hand.
Reverse both input strings to start multiplication from the least significant digits.
Handle negative signs by checking the last characters of the strings and
popping
them if necessary.Remove
trailing
zeros from both strings.Initialize an output string of length
len1 + len2
with '0'.Iterate through each digit of the second number and multiply it with each digit of the first number, adding the result to the corresponding position in the output string.
Handle
carry
duringmultiplication
andaddition
.Remove
trailing zeros
from the output string.Add a
negative
sign to the output string if either of the input strings was negative.Reverse the output string to obtain the correct result.
Explanation with Example
Suppose we want to multiply "123" and "45":
Reverse both strings:
321
and54
.No negative signs.
No trailing zeros.
Initialize the result as "00000".
Multiply and add:
on
3 * 5 = "51000"
on
3 * 4 = "53100"
on
2 * 5 = "53200"
on
2 * 4 = "53010"
on
1 * 5 = "53510"
on
1 * 4 = "53550"
Handle carry if any (none in this case) so
out = "53550"
.Remove trailing zeros, leaving
"53550"
.No negative sign needed.
Reverse the result to get
"5535"
.
Time and Auxiliary Space Complexity
Time Complexity:
O(len1 * len2)
, wherelen1
is the length of the first string andlen2
is the length of the second string.Auxiliary Space Complexity:
O(len1 + len2)
, as we use an output string of lengthlen1 + len2
.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated