// Add two numbers in string.cpp : Defines the entry point for the console application.
/*
You have two numbers in string form, write a function that sums them and returns the result.
Input: 1567,789
Output: 2356
*/
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
string addtwonum (string a, string b){
int len1 = a.length();
int len2 = b.length();
int vc = 0, va = 0, vb = 0, sum = 0, i, j;
char remain ='0';
string res;
for(i= len1-1,j= len2-1;i >=0 && j>=0;--i,--j){
va = a[i]-'0';
vb = b[j]-'0';
sum = va + vb + vc;
remain = sum %10 + '0';
vc = sum /10;
res.insert(0,1,remain);
}
string l = i>=0? a : b;
int k = i>=0? i : j;
for(;k>=0;--k){
sum = l[k] - '0' + vc;
remain = sum %10 + '0';
vc = sum /10;
res.insert(0,1,remain);
}
if(vc){
res.insert(0,1,vc+'0');
}
return res;
}
int main(){
string a,b,c;
while(1){
cin>> a;
cin>> b;
c = addtwonum (a,b);
cout <<a<<endl<<b<<endl<<c<<endl;
}
return 0;
}
No comments:
Post a Comment