Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions bit_manipulation/add_Binary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
def add_Binary(a: str, b: str) -> str:

Check failure on line 1 in bit_manipulation/add_Binary.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N802)

bit_manipulation/add_Binary.py:1:5: N802 Function name `add_Binary` should be lowercase

Check failure on line 1 in bit_manipulation/add_Binary.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N999)

bit_manipulation/add_Binary.py:1:1: N999 Invalid module name: 'add_Binary'

Check failure on line 1 in bit_manipulation/add_Binary.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N802)

bit_manipulation/add_Binary.py:1:5: N802 Function name `add_Binary` should be lowercase

Check failure on line 1 in bit_manipulation/add_Binary.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N999)

bit_manipulation/add_Binary.py:1:1: N999 Invalid module name: 'add_Binary'
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))
Loading