Skip to content
Merged
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
14 changes: 9 additions & 5 deletions maths/addition_without_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@

def add(first: int, second: int) -> int:
"""
Implementation of addition of integer
Add two integers using bitwise operations instead of arithmetic operators.
- XOR (^) to add bits without carrying
- AND (&) to calculate carry bits
- Left shift (<<) to move the carry to the correct position

Examples:
>>> add(3, 5)
Expand All @@ -19,10 +22,11 @@ def add(first: int, second: int) -> int:
-5
>>> add(0, -7)
-7
>>> add(-321, 0)
-321
>>> add(-321, 1)
-320
"""
while second != 0:

while second != 0: # Continue until there is no carry left
c = first & second
first ^= second
second = c << 1
Expand All @@ -36,4 +40,4 @@ def add(first: int, second: int) -> int:

first = int(input("Enter the first number: ").strip())
second = int(input("Enter the second number: ").strip())
print(f"{add(first, second) = }")
print(f"{first = }, {second = }, {add(first, second) = }")
Loading