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
25 changes: 25 additions & 0 deletions bit_manipulation/Fit binaryadd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
def addBinary(a: str, b: str) -> str:

Check failure on line 1 in bit_manipulation/Fit binaryadd.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N802)

bit_manipulation/Fit binaryadd.py:1:5: N802 Function name `addBinary` should be lowercase

Check failure on line 1 in bit_manipulation/Fit binaryadd.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N999)

bit_manipulation/Fit binaryadd.py:1:1: N999 Invalid module name: 'Fit binaryadd'
i, j = len(a) - 1, len(b) - 1
carry = 0
result = []

while i >= 0 or j >= 0 or carry:
total = carry

if i >= 0:
total += int(a[i])
i -= 1
if j >= 0:
total += int(b[j])
j -= 1

result.append(str(total % 2)) # current bit
carry = total // 2 # carry for next bit

return ''.join(reversed(result))
# Example usage
if __name__ == "__main__":
a = "1010"
b = "1011"
print("Input: a =", a, ", b =", b)
print("Output:", addBinary(a, b))
Loading