Skip to content

Commit 3ce27d2

Browse files
authored
feat: Add Binary addition algorithm in C++
this program adds two binary numbers given as strings and returns their sum as a binary string.
1 parent ba0d3ff commit 3ce27d2

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

bit_manipulation/add_binary.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <iostream>
2+
#include <string>
3+
#include <algorithm>
4+
5+
std::string add_binary(std::string a, std::string b) {
6+
int i = a.size() - 1;
7+
int j = b.size() - 1;
8+
int carry = 0;
9+
std::string result = "";
10+
11+
while (i >= 0 || j >= 0 || carry) {
12+
int sum = carry;
13+
if (i >= 0) sum += a[i--] - '0'; // convert char to int
14+
if (j >= 0) sum += b[j--] - '0';
15+
result += (sum % 2) + '0'; // convert int back to char
16+
carry = sum / 2;
17+
}
18+
19+
std::reverse(result.begin(), result.end());
20+
return result;
21+
}
22+
23+
int main() {
24+
std::string a = "1010";
25+
std::string b = "1011";
26+
std::cout << "Sum: " << add_binary(a, b) << std::endl; // Output: 10101
27+
return 0;
28+
}

0 commit comments

Comments
 (0)