-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSum_Two_LargeNums (string).cpp
More file actions
99 lines (90 loc) · 1.88 KB
/
Copy pathSum_Two_LargeNums (string).cpp
File metadata and controls
99 lines (90 loc) · 1.88 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Given two non-negative numbers X and Y.
// The task is calculate the sum of X and Y.
// If the number of digits in sum (X+Y) are equal to the number of digits in X,
// then print sum, else print X.
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
string Sum_LargeNums(string str1, string str2)
{
int i, j, n, m, x, carry=0;
string res = "";
n = str1.size();
m = str2.size();
i = n-1;
j = m-1;
while(i>(-1) && j>(-1))
{
x = (str1[i]-'0') + (str2[j]-'0') + carry;
if(x / 10 == 1)
{
carry = 1;
res = res + to_string(x % 10);
}
else
{
carry = 0;
res = res + to_string(x % 10);
}
i--;
j--;
}
while(j > (-1))
{
x = (str2[j]-'0') + carry;
if(x / 10 == 1)
{
carry = 1;
res = res + to_string(x % 10);
}
else
{
carry = 0;
res = res + to_string(x % 10);
}
j--;
}
while(i > (-1))
{
x = (str1[i]-'0') + carry;
if(x / 10 == 1)
{
carry = 1;
res = res + to_string(x % 10);
}
else
{
carry = 0;
res = res + to_string(x % 10);
}
i--;
}
if(carry == 1)
res = res + to_string(carry);
reverse(res.begin(), res.end());
if(res.size() == str1.size())
return res;
else
return str1;
}
int main()
{
// x = 25;
// y = 23;
// x = 100;
// y = 1000;
int t;
cout<<"\nEnter the Number of Testcases: ";
cin>>t;
while(t)
{
string x, y, ans;
cout<<"\nEnter the X and Y: ";
cin>>x>>y;
ans = Sum_LargeNums(x, y);
cout<<"The Resultant Answer is: "<<ans<<"\n";
t--;
}
cout<<"\n";
return 0;
}