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 addBinary(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 `addBinary` should be lowercase
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file bit_manipulation/add_binary.py, please provide doctest for the function addBinary

Variable and function names should follow the snake_case naming convention. Please update the following name accordingly: addBinary

Please provide descriptive name for the parameter: a

Please provide descriptive name for the parameter: b

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:", addBinary(a, b))
Loading