Skip to content

Commit 1c4493a

Browse files
authored
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
1 parent 52602ea commit 1c4493a

File tree

1 file changed

+5
-14
lines changed

1 file changed

+5
-14
lines changed

maths/addition_without_arithmetic.py

+5-14
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,6 @@
1-
"""
2-
Illustrate how to add the integer without arithmetic operation
3-
Author: suraj Kumar
4-
Time Complexity: 1
5-
https://en.wikipedia.org/wiki/Bitwise_operation
6-
"""
7-
8-
91
def add(first: int, second: int) -> int:
102
"""
11-
Implementation of addition of integer
3+
Add two integers using bitwise operations.
124
135
Examples:
146
>>> add(3, 5)
@@ -23,17 +15,16 @@ def add(first: int, second: int) -> int:
2315
-321
2416
"""
2517
while second != 0:
26-
c = first & second
27-
first ^= second
28-
second = c << 1
18+
carry = first & second # Calculate carry
19+
first = first ^ second # Add without carry
20+
second = carry << 1 # Prepare carry for next iteration
2921
return first
3022

31-
3223
if __name__ == "__main__":
3324
import doctest
3425

3526
doctest.testmod()
3627

3728
first = int(input("Enter the first number: ").strip())
3829
second = int(input("Enter the second number: ").strip())
39-
print(f"{add(first, second) = }")
30+
print(f"The sum is: {add(first, second)}")

0 commit comments

Comments
 (0)