-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubtract.cpp
81 lines (80 loc) · 1.76 KB
/
subtract.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
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
string a,b;
cin>>a>>b;
string temp; // to swap the strings
int d=0,i=0;
if(a.length()<b.length()) // to make sure string a is bigger than string b
{
temp=a; // to swap the strings
a=b;
b=temp;
}
if(a.length()==b.length())
{
while(1)
{
if(a[i]>b[i])
{
break;
}
else
if(a[i]<b[i])
{
temp=a;
b=a;
a=b;
break;
}
i++;
if(i==a.length()) // if both strings equal break the loop
{
d=1;
break;
}
}
}
if(d==1)
{
cout<<'0'<<endl;
return 0;
}
string ans="";
int s=0,c=0,ka=a.length()-1,kb=b.length()-1; // variable c to store carry
while(ka>=0||kb>=0) // string a is bigger than string b so ka >= kb so kb first become zero
{
if(ka>=0&&kb>=0)
{
s=(a[ka--]-'0')-(b[kb--]-'0')-c;
}
else
if(ka>=0)
{
s=(a[ka--]-'0')-c;
}
if(s<0)
{
s+=10;
c=1;
}
else
c=0;
char cc= s+48; // to convert integer to character
ans = cc+ans;
}
long k=-1;
for(int i=0;i<ans.length();i++)
if(ans[i]=='0')
k=i;
else
break;
ans.erase(0,k+1);
cout<<ans<<endl;
}
}