Reputation: 455
I coded a simple solution which multiplied 2 integers given as strings and returned the product as a string. But it doesn't work for big values and I'm not allowed to use the Big-Integer library.
This is my current solution.
class Solution {
public String multiply(String num1, String num2) {
int numOne = 0;
int numTwo = 0;
for(char c : num1.toCharArray()){
if((int)(c-'0') >= 0 && (int)(c-'0') <= 9){
numOne = numOne*10 + (int)(c-'0');
}
}
for(char c : num2.toCharArray()){
if((int)(c-'0') >= 0 && (int)(c-'0') <= 9){
numTwo = numTwo*10 + (int)(c-'0');
}
}
return numOne*numTwo + "";
}
}
I got an error in the following test case:
Input:
"123456789"
"987654321"
Output:
"-67153019"
Expected:
"121932631112635269"
What changes should I make so as to be able to multiply large numbers also?
Upvotes: 0
Views: 398
Reputation: 203
For this, you can refer to the Karatsuba Multiplication algorithm.
You can do this too.
There are samples of this solution too on the internet. You will find it.
Upvotes: 3