Reputation: 23
How do I get the sum of two strings that are numbers? For example:
string num1 = "12";
string num2 = "4";
string sum = num1 + num2;
So string sum
will equal "16"
How do I do this in c++?
I tried doing it with ascii characters but it does not work I cannot convert the string to an integer as well
Upvotes: 1
Views: 27431
Reputation: 166
The answer to your question can be written like this
string addStrings(string num1, string num2) {
string res="";
int n=num1.size();
int m=num2.size();
int carry=0;
int j;
for(int i=n-1,j=m-1;i>=0 || j>=0;i--,
j--){
int a;
if(i>=0){
a=((int)(num1[i])-48);
}
else {
a=0;
}
int b;
if(j>=0){
b=((int)(num2[j])-48);
}
else{
b=0;
}
cout<<num1[i]<<" "<<num2[i]<<endl;
cout<<a<<" "<<b<<endl;
int sum=carry+a+b;
int u=sum%10;
res+=u;
carry=sum/10;
}
res+=carry;
cout<<res<<endl;
reverse(res.begin(),res.end());
return res;
}
I added cout statements to check what's going on inside the function
Upvotes: 1
Reputation: 37691
To add large integers using string, you can do something like this.
string doSum(string a, string b)
{
if(a.size() < b.size())
swap(a, b);
int j = a.size()-1;
for(int i=b.size()-1; i>=0; i--, j--)
a[j]+=(b[i]-'0');
for(int i=a.size()-1; i>0; i--)
{
if(a[i] > '9')
{
int d = a[i]-'0';
a[i-1] = ((a[i-1]-'0') + d/10) + '0';
a[i] = (d%10)+'0';
}
}
if(a[0] > '9')
{
string k;
k+=a[0];
a[0] = ((a[0]-'0')%10)+'0';
k[0] = ((k[0]-'0')/10)+'0';
a = k+a;
}
return a;
}
int main()
{
string result = doSum("1234567890", "123789456123");
cout << result << "\n";
}
Output
125024024013
Reference: See the complete code at Ideone.com
Upvotes: 4
Reputation: 1
The flat answer is
string sum = std::to_string(std::stoi(num1) + std::stoi(num2));
See the Live Demo.
The broader answer as for your comment is:
You cannot use that technique to do math with big integer values.
That requires using an appropriate 3rd party library.
Upvotes: 4