Most Probable Interview Question:

Add two numbers without using Addition Operator by both normal and Recursion method.  The condition given here is, we should not use Addition Operator.  Let us think about other ways now as we are restricted not to use + operator.

Logic is, Bitwise operator can be used for solving this problem.  First, we can take two integers variable x and y

assume – They are x=5 and y=4

check the below logic while y=0 then print x

take one another variable like z

z=x&y  ,  x=x^y  ,  y=z<<1

We can change the x and y value in binary format likewise 5=101 and 4=100 , execution is

&                              ^                   y=<<1

x  = 101                      101              z<<1

y  = 100                     100             100<<1

———                     ——         ———–

z = 100                 x=  001           y=1000

&                              ^                     y= <<1

x  = 001                      0101           y= z<<1

y  =1000                     1000          0000<<1

———                     ——            ———–

z =0000                 x= 1001         y=00000

Now ,y=0 then we will print x

now x=1001 corresponding decimal value is 9

Program for Normal method :

public class Eg1 {
public static void main(String[] args){
int x=5,y=4,z;
while(y!=0){
z=x&y;
x=x^y;
y=z<<1;
}
System.out.println(x);
}

}

Program for Recursion Method :

public class Eg {
int add(int x, int y)
{
if (y == 0)
return x;
else
return add( x ^ y, (x & y) << 1);
}
public static void main(String[] args) {
Eg e = new Eg();
System.out.println(e.add(5, 7));
}

}