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!

9
  • 6
    Maybe x - (- y) ? Commented Oct 14, 2016 at 11:16
  • 1
    @coredump did the same thing but he insisted me not to do that !! Commented Oct 14, 2016 at 12:01
  • 3
    @2501 but the algorithm doesn't change Commented Oct 14, 2016 at 12:18
  • 1
    @Anjaneyulu Unfortunately, this position required you to be able to perform mind reading. Commented Oct 14, 2016 at 12:46
  • 1
    @Matt That is undefined behaviour, as it has there is unsequenced side-effects on variables that are read on multiple subexpressions. Or to put it short: your expression is broken and illegal. Commented Oct 14, 2016 at 13:13

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.