Multiply Strings
String Math
Last updated
Was this helpful?
String Math
Last updated
Was this helpful?
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string. You must not have any leading zeroes.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
For example:
We are simulating the multiplication process by taking numbers digit by digit, and keep multiplying the digit with the other number and maintaining the sum in a separate array.
We can get the index in the result array of where the product of the two digits should be placed by taking the addition of the original index of the two numbers and adding 1 (this positon is also where the last carry digit will be present)
If a carry digit is already in this position, we sum it to the product, take the quotient, and place the carry in the next positon
Different from Add Strings, we have two for loops, instead of a while loop and two pointers, because we need to multiply each digit in one number with all the other digits in the other number.
Need two for loops to simulate multiplying each digit in one number with the digits in the other number
Need a "sum" array that will simulate all the addition operations when a carry is needed to be added to the product of two digits. This sum array will also be our output array
In our "sum" array, we are storing the quotient of a product in one slot and the remainder (which is the carry variable) in the other slot.
Need to check for leading zeroes
Time:
Space: