mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-04-06 22:05:54 +00:00
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:
parent
52602ea5b6
commit
1c4493ab3f
@ -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)}")
|
||||||
|
Loading…
x
Reference in New Issue
Block a user