forked from akhiluanandh/utility-functions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add_numbers_as_strings.cpp
82 lines (76 loc) · 1.34 KB
/
add_numbers_as_strings.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <string>
using namespace std;
int getint(char a)
{
return a-48;
}
char getc(int a)
{
return a+48;
}
string reverse(string a)
{
return string(a.rbegin(), a.rend());
}
string add(string a, string b)
{
string answer;
int carry = 0, temp;
string::reverse_iterator itb = b.rbegin(), ita = a.rbegin();
for(; itb != b.rend() && ita != a.rend(); itb++, ita++)
{
temp = (getint(*itb) + getint(*ita) + carry);
if(temp >= 10)
{
answer.push_back(getc(temp-10));
carry = 1;
}
else
{
answer.push_back(getc(temp));
carry = 0;
}
}
string::reverse_iterator it;
int whichone = 0;
if(itb != b.rend() && (whichone = 2))
it = itb;
else if(ita != a.rend() && (whichone = 1))
it = ita;
if(whichone)
{
string notover = (whichone == 1)?a:b;
for(;it != notover.rend(); itb++)
{
if(carry > 0)
{
if(*it > 8)
answer.push_back(getc(getint(*it)+carry-10));
else
{
answer.push_back(getc(getint(*it)+carry));
carry = 0;
}
}
}
}
if(carry)
answer.push_back(getc(carry));
answer = reverse(answer);
return answer;
}
int main()
{
int t, n;
long long k;
string sn, sk;
cin>>t;
while(t--)
{
cin>>sn;
cin>>sk;
cout<<add(sn, sk)<<"\n";
}
return 0;
}