You are on page 1of 2

function to add tow binary number using queue data structure in c++

#include <iostream>
#include <queue>
using namespace std;

// Function to add two binary numbers using queues


queue<int> addBinary(queue<int>& num1, queue<int>& num2) {
queue<int> result;
int carry = 0;

while (!num1.empty() || !num2.empty() || carry) {


int bit1 = 0, bit2 = 0;

if (!num1.empty()) {
bit1 = num1.front();
num1.pop();
}

if (!num2.empty()) {
bit2 = num2.front();
num2.pop();
}

int sum = bit1 + bit2 + carry;


result.push(sum % 2);
carry = sum / 2;
}

return result;
}

int main() {
string binary1, binary2;
cout << "Enter binary number 1: ";
cin >> binary1;
cout << "Enter binary number 2: ";
cin >> binary2;

queue<int> num1, num2;

// Converting input binary strings to queues of integers


for (char c : binary1)
num1.push(c - '0'); // Convert char to integer

for (char c : binary2)


num2.push(c - '0'); // Convert char to integer

// Adding binary numbers using the addBinary function


queue<int> result = addBinary(num1, num2);

// Printing the binary sum


cout << "Binary sum: ";
while (!result.empty()) {
cout << result.front();
result.pop();
}
cout << endl;
return 0;
}

You might also like