Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Compute the sum of two given binary strings

C++ Math: Exercise-22 with Solution

Write a C++ program to compute the sum of two given binary strings. Return result will be a binary string and input strings should not be blank and contains only 1 or 0 charcters.

Sample Input: bstr1 = "10"
bstr2 = "1"
Sample Output: 10 + 1 = 11

Sample Input: bstr1 = "1100"
bstr2 = "1010"
Sample Output: 1100 + 1010 = 10110

Sample Solution:

C++ Code :

#include <iostream>

using namespace std;

string binary_add(string bstr1, string bstr2) {
        int size = max(bstr1.size(), bstr2.size());
        int temp = 0;

        string result_str = "";
        for(auto i = 0; i < size; ++i)
        {
            int digit1 = (i + 1 <= bstr1.size()) ? bstr1[bstr1.size() - 1 - i] - '0' : 0;
            int digit2 = (i + 1 <= bstr2.size()) ? bstr2[bstr2.size() - 1 - i] - '0' : 0;
            int number = (digit1 + digit2 + temp);
            temp = number / 2;
            result_str = to_string(number % 2) + result_str;
        }

        if (temp > 0)
        {
            result_str = to_string(temp) + result_str;
        }

        return result_str;
    }

int main() {
    string bstr1 = "10";
    string bstr2 = "1";
    cout << "\n" << bstr1 << " + " << bstr2 <<" = " << binary_add(bstr1, bstr2) << endl;
    bstr1 = "1100";
    bstr2 = "1010";
    cout << "\n" << bstr1 << " + " << bstr2 <<" = " << binary_add(bstr1, bstr2) << endl;
    bstr1 = "10";
    bstr2 = "10";
    cout << "\n" << bstr1 << " + " << bstr2 <<" = " << binary_add(bstr1, bstr2) << endl;			    
    return 0;
}

Sample Output:

10 + 1 = 11

1100 + 1010 = 10110

10 + 10 = 100

Flowchart:

Flowchart: Compute the sum of two given binary strings

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to check if a given string is a decimal number or not.

Next: Write a C++ program to compute square root of a given non-negative integer.

What is the difficulty level of this exercise?