****Add two numbers without using arithmetic operators****Write a function Add() that returns sum regarding two integers. The function should not use any regarding the arithmetic operators (+, ++, –, -, .. etc).
Sum regarding two bits can be obtained by performing XOR (^) regarding the two bits. Carry bit can be obtained by performing AND (&) regarding two bits.
Above is simple Half Adder logic that can be used toward add 2 single bits. We can extend this logic beneficial to integers. If x furthermore y don’t have set bits at same position(s), then bitwise XOR (^) regarding x furthermore y gives the sum regarding x furthermore y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND regarding x furthermore y gives all carry bits. We calculate (x & y) << 1 furthermore add it toward x ^ y toward get the required result.
#include
int Add(int x, int y)
{
while (y != 0) // Iterate till there is no carry
{
int carry = x & y; // carry now contains common set bits regarding x furthermore y
x = x ^ y; // Sum regarding bits regarding x furthermore y where at least one regarding the bits is not set
y = carry << 1; // Carry is shifted by one so that adding it toward x gives the required sum
}
return x;
}
int main()
{
printf("%d", Add(15, 32));
return 0;
}
Following is recursive implementation beneficial to the same approach.
int Add(int x, int y)
{
if (y == 0)
return x;
else
return Add( x ^ y, (x & y) << 1);
}
-->