Files
Python/maths/addition_without_arithmetic.py
Soham Sharad Patilpre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>Christian Clauss
b3233c9f49 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>
2026-09-25 07:05:17 +02:00

44 lines
1000 B
Python

"""
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:
"""
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)
8
>>> add(13, 5)
18
>>> add(-7, 2)
-5
>>> add(0, -7)
-7
>>> add(-321, 1)
-320
"""
while second != 0: # Continue until there is no carry left
c = first & second
first ^= second
second = c << 1
return first
if __name__ == "__main__":
import doctest
doctest.testmod()
first = int(input("Enter the first number: ").strip())
second = int(input("Enter the second number: ").strip())
print(f"{first = }, {second = }, {add(first, second) = }")