October 23, 2013

Interview Question - Add two integers without using + sign

This seems simple enough but to those not too comfortable with bits, it's a bit tricky (ha...)

public int AddWithBits(int a, int b) {
   while (b > 0) {
      var sum = a ^ b;
      var carry = (a & b) << 1;
      a = sum;
      b = carry;
   }

   return a;
}