Sum of two large number as string in C++
Sum of 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();
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;
}
int main(){
cout << sumOfTwoStringAsNumber("1234","9874")<<endl;
return 0;
}
Comments
Post a Comment