From d63c6a134cf256f49c6f665dc6e9f7dffa668908 Mon Sep 17 00:00:00 2001 From: Sujal Gupta Date: Mon, 6 Oct 2025 18:48:22 +0530 Subject: [PATCH] feat: Add Binary addition algorithm in Python MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This program adds two binary numbers given as strings and returns their sum as a binary string. Based on LeetCode Problem 67 — Add Binary. --- bit_manipulation/add_Binary.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 bit_manipulation/add_Binary.py diff --git a/bit_manipulation/add_Binary.py b/bit_manipulation/add_Binary.py new file mode 100644 index 000000000000..a4ac64b1f804 --- /dev/null +++ b/bit_manipulation/add_Binary.py @@ -0,0 +1,27 @@ +def add_Binary(a: str, b: str) -> str: + i, j = len(a) - 1, len(b) - 1 # start from the end of both strings + carry = 0 + result = [] + + while i >= 0 or j >= 0 or carry: + total = carry + + if i >= 0: + total += int(a[i]) # convert char to int + i -= 1 + if j >= 0: + total += int(b[j]) + j -= 1 + + result.append(str(total % 2)) # current bit + carry = total // 2 # update carry + + return ''.join(reversed(result)) # reverse the result to get correct order + + +# Example usage +if __name__ == "__main__": + a = "1010" + b = "1011" + print("Input: a =", a, ", b =", b) + print("Output:", add_Binary(a, b))