# Add two numbers without using arithmetic operators

Problem Statement:

Add two numbers without using arithmetic operators

Write a function Add() that returns sum of two integers.

The function should not use any of the arithmetic operators (+, ++, –, -, .. etc).

**We suggest you think about a solution before reading further…**

Solution:

Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result. The same logic can be implemented iteratively as well as recursively as shown below.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
//Add two numbers without using arithmetic operators public class AddTwoNumbers { public static void main(String[] args) { int a = 10; int b = 20; int sum1 = addIterative(a, b); System.out.println("Sum by iterative method : " + sum1); int sum2 = addRecursion(a,b); System.out.println("Sum by recursive method : " + sum2); } private static int addIterative(int a, int b) { //iterate till second no becomes 0 while(b != 0){ // carry now contains common set bits of 'a' and 'b' int carry = a & b; // Sum of bits of 'a' and 'b' where at least one of the bits is not set a = a ^ b; // Carry is shifted by one so that adding it to 'a' gives the required sum b = carry << 1; } return a; } private static int addRecursion(int a, int b) { if(b == 0){ return a; }else{ //Pass Sum, Carry shifted by 1 recursively return addRecursion(a ^ b, (a & b) << 1); } } } |

Output:

1 2 |
Sum by iterative method : 30 Sum by recursive method : 30 |