In this article, we will learn about python program to add two numbers without using addition operator (i.e. + operator)
Getting Started
The task is use to add two numbers in python without using + operator.
In other words,
We have to add two numbers a and b without using + operator.
Add Two Numbers in Python Without + operator
We will be using Half Adder Logic to add two numbers.
Pseudo Algorithm using Half Adder Logic
- Let’s say we want to add two numbers a and b.
- Step 1: If both numbers don’t have set bit (i.e. 1) at same position, simply XOR operation (^) gives sum of a and b.
- Step 2: Else if they have set bits at same position, AND operation (bitwise &) provides carry bits at all position.
- Step 3: Now, left shift carry bits by 1 and add it to result obtained it by performing XOR operation.
- Step 4: Repeat step 1, step 2 and step 3 until carry is zero (i.e. 0).
Python Program
def addWithoutOperator(a, b): |
print ( "Sum = " , addWithoutOperator( 15 , 31 )) |
Output:
Python Program to Add Two Numbers Using Recursion
We can write above program using recursion to add two numbers in python as shown below –
def addWithoutOperator(a, b): |
return addWithoutOperator( a ^ b, (a & b) << 1 ) |
print ( "Sum = " , addWithoutOperator( 15 , 31 )) |
Output:
In above program, calling addWithoutOperator method until carry is 0.
Time complexity: O(log b)
Space complexity: O(1)
That’s how we can write python program to add two numbers without using addition operator.
Learn more python programs at – https://tutorialwing.com/python-tutorial/