How to add two numbers without using arithmetic operators
Overview
Consider a problem where we have to find the sum of two numbers without using the arithmetic operators +, -, *, and /.
Example 1:
- Input: 5, 8
- Output: 13
Example 2:
- Input: 5, -8
- Output: -3
Solution
In half adder logic, we can add two bits by performing their XOR (^), the sum bit. We can obtain the carry bit by performing AND (&) of two bits.
We can apply the same logic to obtain the sum of two numbers.
The steps of the algorithm are as follows:
- Until there is no carry element, perform the below steps:
- Find the carry by performing AND (
&) onxandy. - Find the sum by performing XOR (
^) onxandy. Thex ^ yis assigned to .``. - The carry is left-shifted by one so that adding it to
xgives the required sum. The left-shifted carry is assigned toy.
- Find the carry by performing AND (
- Return
xas the sum will bex.
Code
public class Main {static int iterative_add(int x, int y) {while(y != 0){int carry = x & y;x = x ^ y;y = carry << 1;}return x;}public static void main(String[] args) {int x = 10;int y = 15;int sum = iterative_add(x, y);System.out.println(String.format("(Iterative sum) %d + %d = %d", x, y, sum));}}
Explanation
- Lines 3–10: We define the
iterative_add()method to implement the above solution iteratively. - Line 13: We define
x. - Line 14: We define
y. - Line 15: We invoke the
iterative_add()method to calculate the sum ofxandy. - Line 16: We print the sum.