0

I was asked this question in an interview:

How to add two variables without using a '+' operator?

The interviewer asked me and I could not answer, even though I am a good C programmer!

Draken
  • 3,134
  • 13
  • 34
  • 54
Anjaneyulu
  • 434
  • 5
  • 21

1 Answers1

3

Using bitwise operators you can add two numbers. Try below:

   int Sum(int a, int b)
    {
        // Iterate till there is no carry  
        while (b != 0)
        {
            // now carry 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;
    }

Using Increment and decrement operators you can add two numbers. The other way may be like:

int Sum(int a, int b)
{
    // Iterate till there b becomes zero
    while (b--)
    {
        a++;
    }
    return a;
}
Stubborn
  • 780
  • 1
  • 5
  • 20