From 3ce27d20652a946fb15d536f9fa0add82df78ab5 Mon Sep 17 00:00:00 2001 From: Sujal Gupta Date: Mon, 6 Oct 2025 21:32:17 +0530 Subject: [PATCH] feat: Add Binary addition algorithm in C++ this program adds two binary numbers given as strings and returns their sum as a binary string. --- bit_manipulation/add_binary.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 bit_manipulation/add_binary.cpp diff --git a/bit_manipulation/add_binary.cpp b/bit_manipulation/add_binary.cpp new file mode 100644 index 0000000000..e3959c004b --- /dev/null +++ b/bit_manipulation/add_binary.cpp @@ -0,0 +1,28 @@ +#include +#include +#include + +std::string add_binary(std::string a, std::string b) { + int i = a.size() - 1; + int j = b.size() - 1; + int carry = 0; + std::string result = ""; + + while (i>= 0 || j>= 0 || carry) { + int sum = carry; + if (i>= 0) sum += a[i--] - '0'; // convert char to int + if (j>= 0) sum += b[j--] - '0'; + result += (sum % 2) + '0'; // convert int back to char + carry = sum / 2; + } + + std::reverse(result.begin(), result.end()); + return result; +} + +int main() { + std::string a = "1010"; + std::string b = "1011"; + std::cout << "Sum: " << add_binary(a, b) << std::endl; // Output: 10101 + return 0; +}

AltStyle によって変換されたページ (->オリジナル) /