Skip to content

Commit b3233c9

Browse files
Soham-1616pre-commit-ci[bot]cclauss
authored
Clarify bitwise operations used in addition without arithmetic (#14059)
* Document addition function using bitwise operations Added docstring explaining the bitwise addition method. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Refactor addition function documentation and output Updated docstring to clarify the use of bitwise operations for addition. Modified the output format of the result to include both input values. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 7a8079f commit b3233c9

1 file changed

Lines changed: 9 additions & 5 deletions

File tree

‎maths/addition_without_arithmetic.py‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@
88

99
def add(first: int, second: int) -> int:
1010
"""
11-
Implementation of addition of integer
11+
Add two integers using bitwise operations instead of arithmetic operators.
12+
- XOR (^) to add bits without carrying
13+
- AND (&) to calculate carry bits
14+
- Left shift (<<) to move the carry to the correct position
1215
1316
Examples:
1417
>>> add(3, 5)
@@ -19,10 +22,11 @@ def add(first: int, second: int) -> int:
1922
-5
2023
>>> add(0, -7)
2124
-7
22-
>>> add(-321, 0)
23-
-321
25+
>>> add(-321, 1)
26+
-320
2427
"""
25-
while second != 0:
28+
29+
while second != 0: # Continue until there is no carry left
2630
c = first & second
2731
first ^= second
2832
second = c << 1
@@ -36,4 +40,4 @@ def add(first: int, second: int) -> int:
3640

3741
first = int(input("Enter the first number: ").strip())
3842
second = int(input("Enter the second number: ").strip())
39-
print(f"{add(first, second) = }")
43+
print(f"{first = }, {second = }, {add(first, second) = }")

0 commit comments

Comments
 (0)