Why isn't any value being pushed to the 'res' string?

Viewed 54

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.

1 Answers

If you look at the ASCII table, 49 is the ASCII value of char '1'. Thus it totally makes sense that the following:

res.push_back(carry);

...inserts '1' into res because at that point, carry's value is 49 and the variable carry is an integer. Thus, C++ inserts the character with the ASCII value 49, ie, 1.

So use this instead:

res += std::to_string(carry); // std::to_string converts many basic data types to std::string

The reason I am not using push_back here is because push_back can only insert a single character at one time. So you can use the += to add the contents of std::to_string(carry) to res.

Related