Add two numbers without using arithmetic operators

Posted on Updated on

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.

Output:

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.