Update addition_without_arithmetic.py

I have made few changes for more clarity.

1. Wrote comments making the logic clearer
2. Changed the var name from c to carry for more clarity
This commit is contained in:
Cgarg547 2024-10-29 02:52:38 -04:00 committed by GitHub
parent 52602ea5b6
commit 1c4493ab3f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,14 +1,6 @@
"""
Illustrate how to add the integer without arithmetic operation
Author: suraj Kumar
Time Complexity: 1
https://en.wikipedia.org/wiki/Bitwise_operation
"""
def add(first: int, second: int) -> int: def add(first: int, second: int) -> int:
""" """
Implementation of addition of integer Add two integers using bitwise operations.
Examples: Examples:
>>> add(3, 5) >>> add(3, 5)
@ -23,12 +15,11 @@ def add(first: int, second: int) -> int:
-321 -321
""" """
while second != 0: while second != 0:
c = first & second carry = first & second # Calculate carry
first ^= second first = first ^ second # Add without carry
second = c << 1 second = carry << 1 # Prepare carry for next iteration
return first return first
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest
@ -36,4 +27,4 @@ if __name__ == "__main__":
first = int(input("Enter the first number: ").strip()) first = int(input("Enter the first number: ").strip())
second = int(input("Enter the second number: ").strip()) second = int(input("Enter the second number: ").strip())
print(f"{add(first, second) = }") print(f"The sum is: {add(first, second)}")