We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent ba0d3ff commit 3ce27d2Copy full SHA for 3ce27d2
bit_manipulation/add_binary.cpp
@@ -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