Its a program to add two binary numbers stored in strings and storing the result in a string.
This is my code :
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
string a = "11", b = "1";
int i, j, carry = 0;
string res;
i = a.length() - 1;
j = b.length() - 1;
while (i >= 0 && j >= 0)
{
res.push_back((char)(a[i] + b[j] + carry) % 2);
cout << "0";
carry = (a[i] + b[j] + carry) / 2;
i--;
j--;
}
if (i > 0)
{
while (i >= 0)
{
res.push_back((char)(a[i] + 0 + carry) % 2);
carry = (a[i] + 0 + carry) / 2;
}
}
if (j > 0)
{
while (j >= 0)
{
res.push_back((char)(0 + b[j] + carry) % 2);
carry = (0 + b[j] + carry) / 2;
}
}
if (carry)
res.push_back(carry);
cout << endl
<< "-1";
cout << endl
<< res;
}
output:
0
-1
1
Only 1 is pushed into res by the last if(carry) block. Thanks in advance.