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:

  1. Until there is no carry element, perform the below steps:
    1. Find the carry by performing AND (&) on x and y.
    2. Find the sum by performing XOR (^) on x and y. The x ^ y is assigned to .``.
    3. The carry is left-shifted by one so that adding it to x gives the required sum. The left-shifted carry is assigned to y.
  2. Return x as the sum will be x.

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 of x and y.
  • Line 16: We print the sum.

Free Resources