Integer multiplication using strings as input C++
Whenever I feed single digit input to the following code, the answer comes
out to be in 4 digits.
#include <iostream>
#include <stdio.h>
using namespace std;
int makeEqual(string &s1, string &s2)
{
int len1 = s1.length();
int len2 = s2.length();
//cout<<"Lenght 1 :: "<<len1<<endl;
//cout<<"Lenght 2 :: "<<len2<<endl;
if(len1>len2)
{
for(int i=0; i<(len1-len2); i++)
s2='0'+s2;
//cout<<"Return value is :: "<<len1<<endl;
return len1;
}
else if(len2>len1)
{
for(int i=0; i<len2-len1; i++)
s1='0'+s1;
//cout<<"Return value is :: "<<len2<<endl;
return len2;
}
else
return len1;
}
int singleMultiply(string s1, string s2)
{
return (s1[0]-'0')*(s2[0]-'0');
}
long int multiply(string a, string b)
{
int n=makeEqual(a,b);
if(n==0) return 0;
if(n==1) return (singleMultiply(a,b));
return 0;
}
int main()
{
cout<<singleMultiply("9","9");
return 0;
}
The output is 0020 instead of 20. Can anyone please explain the logic
behind this?
EDIT: I included all the code I wrote. Actually am new to programming, and
am trying to work out code for Karatsuba Algorithm on base 10.
No comments:
Post a Comment