// Hello stranger. ^_^
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
main(void)
{
int g = 0 , ca = 0 , si;
string a , b , c , blank;
cin >> a >> b;
si = max(a.size() , b.size());
if(a < b)
swap(a , b);
if(a.size() < b.size())
{
blank.resize(si - a.size());
a = blank + a;
}
else
{
blank.resize(si - b.size());
b = blank + b;
}
c.resize(si + 1);
for(int i = si - 1 , k = 0 ; i >= 0 ; i-- , k++)
{
if(isdigit(a.at(i)) == true and isdigit(b.at(i)) == true)
c.at(k) = a.at(i) + b.at(i) - 48 + ca;
else if(isdigit(a.at(i)) == true and isdigit(b.at(i)) == false)
c.at(k) = a.at(i) + ca;
else if(isdigit(b.at(i)) == true and isdigit(a.at(i)) == false)
c.at(k) = b.at(i) + ca;
ca = 0;
if(c.at(k) - 48 >= 10)
{
c.at(k) = c.at(k) - 10;
ca = 1;
g++;
}
}
reverse(c.begin() , c.end());
if(ca == 1)
c.at(0) = '1';
else
c.erase(c.begin());
if(a < b)
swap(a , b);
cout << ' ' << a << endl << '+' << b << endl;
for(int i = 0 ; i <= c.size() ; i++)
cout << '-';
cout << endl << c << endl << "Number of Carries: " << g << endl;
}
// Minor changes for subtractions.
//You may want to combine both of them together.
//But I reckon making a project will help since linkers work faster than a gigantic diver code.
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
main(void)
{
int g = 0 , ca = 0 , si , t = 0;
string a , b , c , blank;
cin >> a >> b;
if(a < b)
{
swap(a , b);
t = 1;
}
si = max(a.size() , b.size());
if(a.size() < b.size())
{
blank.resize(si - a.size());
a = blank + a;
}
else
{
blank.resize(si - b.size());
b = blank + b;
}
c.resize(si + 1);
for(int i = si - 1 , k = 0 ; i >= 0 ; i-- , k++)
{
if(isdigit(a.at(i)) == true and isdigit(b.at(i)) == true)
c.at(k) = a.at(i) - b.at(i) + 48 - ca;
else if(isdigit(a.at(i)) == true and isdigit(b.at(i)) == false)
c.at(k) = a.at(i) - ca;
else if(isdigit(b.at(i)) == true and isdigit(a.at(i)) == false)
{
c.at(k) = b.at(i);
ca = 1;
continue;
}
ca = 0;
if(c.at(k) < 48)
{
c.at(k) += 10;
ca = 1;
g++;
}
}
reverse(c.begin() , c.end());
if(ca == 1 or t == 1)
c.at(0) = '-';
else
c.erase(c.begin());
if(a < b)
swap(a , b);
cout << ' ' << a << endl << '-' << b << endl;
for(int i = 0 ; i <= c.size() ; i++)
cout << '-';
cout << endl << c << endl << "Number of Carries: " << g << endl;
}
// Don't follow my code. It's completely composed out of brute force. Learn algorithm for these type of programs , which I'm still learning. ^_^
No comments:
Post a Comment