Multiply two large number as string in C++
Multiply two large number as string in C++
#include<iostream>
#include<string>
using namespace std;
string sumOfTwoStringAsNumber(string str1, string str2){
string res;
int len1 = str1.length();
int len2 = str2.length();
if (len1 == 0 && len2 == 0)
return "0";
else if (len1 != 0 && len2 == 0)
return str1;
else if (len1 == 0 && len2 != 0)
return str2;
string temp1, temp2;
if (len1 >= len2){
temp1 = str1;
temp2 = str2;
}
else{
temp1 = str2;
temp2 = str1;
int temp = len2;
len2 = len1;
len1 = temp;
}
int diff = len1 - len2;
int i, j, rem;
char ch;
bool flag = false;
j = len1 - 1;
res = "";
for (i = len2 - 1; i >= 0; i--){
ch = temp1[j] + temp2[i] - 48;
if (flag)
ch++;
if (ch > 57)
flag = true;
else
flag = false;
ch = ((ch - 48) % 10) + 48;
res = ch + res;
j--;
}
while (j >= 0){
ch = temp1[j];
if (flag){
ch++;
if (ch > 57){
flag = true;
ch = ((ch - 48) % 10) + 48;
}
else{
flag = false;
}
}
res = ch + res;
j--;
}
if (flag){
res = '1' + res;
}
return res;
}
string mulOfTwoStringAsNumber(string str1, string str2){
string res,temp;
int len1 = str1.length();
int len2 = str2.length();
string temp1, temp2;
if (len1 >= len2){
temp1 = str1;
temp2 = str2;
}
else{
temp1 = str2;
temp2 = str1;
int temp = len2;
len2 = len1;
len1 = temp;
}
int i,x,y,j,z;
char ch;
for (i = len2 - 1; i >= 0; i--){
y = temp2[i] - 48;
z = 0;
temp = "";
for (j = len1 - 1; j >= 0; j--){
x = temp1[j] - 48;
x = x*y;
if (z > 0)
x = x + z;
z = x / 10;
ch = ((x % 10) + 48);
temp =ch+temp;
}
if (z > 0){
ch = z + 48;
temp = ch + temp;
}
res = sumOfTwoStringAsNumber(res, temp);
len1++;
temp1 = temp1 + "0";
}
return res;
}
int main(){
cout << mulOfTwoStringAsNumber("3234", "78");
return 0;
}
Comments
Post a Comment