From 2c65597093efa80a572a6a739d8f13a8d3579c18 Mon Sep 17 00:00:00 2001 From: kumarsurajsk <104374726+kumarsurajsk@users.noreply.github.com> Date: Sun, 30 Oct 2022 18:22:37 +0530 Subject: [PATCH] addition_without_arithmetic (#6830) * Addition_without_arithmetic * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * added_param * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * added_param_in_first_sec * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * change_align * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update Addition_without_arithmetic.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Rename Addition_without_arithmetic.py to addition_without_arithmetic.py * Update addition_without_arithmetic.py * Update addition_without_arithmetic.py Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss --- maths/addition_without_arithmetic.py | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 maths/addition_without_arithmetic.py diff --git a/maths/addition_without_arithmetic.py b/maths/addition_without_arithmetic.py new file mode 100644 index 000000000..409604e4c --- /dev/null +++ b/maths/addition_without_arithmetic.py @@ -0,0 +1,39 @@ +""" +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: + """ + Implementation of addition of integer + + Examples: + >>> add(3, 5) + 8 + >>> add(13, 5) + 18 + >>> add(-7, 2) + -5 + >>> add(0, -7) + -7 + >>> add(-321, 0) + -321 + """ + while second != 0: + 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"{add(first, second) = }")