Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,988 questions

51,933 answers

573 users

How to sum two binary strings in C++

2 Answers

0 votes
#include <iostream>
#include <algorithm>

std::string addBinaryStrings(std::string a, std::string b) {
    std::string result;
    int i = a.length() - 1;
    int j = b.length() - 1;
    int carry = 0;

    while (i >= 0 || j >= 0) {
        int sum = carry;
        if (i >= 0) sum += a[i--] - '0';
        if (j >= 0) sum += b[j--] - '0';
        
        carry = sum > 1 ? 1 : 0;
        
        result.push_back(sum % 2 + '0');
    }

    if (carry != 0) result.push_back(carry + '0');
    
    std::reverse(result.begin(), result.end());
    
    return result;
}

int main() {
    std::string a = "11";
    std::string b = "1";
    std::cout << addBinaryStrings(a, b) << std::endl;

    a = "1010";
    b = "1011";
    std::cout << addBinaryStrings(a, b) << std::endl;
}

    
    
/*
run:
    
100
10101
 
*/

 



answered May 8, 2024 by avibootz
0 votes
#include <iostream>
#include <string>
#include <bitset>

std::string addBinaryStrings(std::string a, std::string b) {
    int num1 = std::stoi(a, nullptr, 2);
    int num2 = std::stoi(b, nullptr, 2);
    
    int sum = num1 + num2;
    
    return std::bitset<16>(sum).to_string();
}

int main() {
    std::string a = "11";
    std::string b = "1";
    std::cout << addBinaryStrings(a, b) << std::endl;
    
    a = "1010";
    b = "1011";
    std::cout << addBinaryStrings(a, b) << std::endl;
}



    
    
/*
run:
    
0000000000000100
0000000000010101
 
*/

 



answered May 8, 2024 by avibootz

Related questions

1 answer 81 views
81 views asked May 8, 2024 by avibootz
1 answer 70 views
1 answer 71 views
1 answer 60 views
1 answer 70 views
1 answer 75 views
1 answer 97 views
...