Sum of Two Integers

LeetCode OJ 371:Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

思路:在不使用运算符求和的问题中,最容易想到的一种方法是借助与、异或和移位操作符。与和移位操作符配合使用可以找到进位,异或操作符能够找到非进位,两者相加得到Sum,由于不允许使用+操作符,所以只能通过这种方式递归下去,直到被加数为0,这时的加数即为两数之和。 

int getSum(int a, int b) {

  if(a == 0) return b;
  if(b == 0) return a;

  while(b)
  {
    int x = a ^ b;
    int y = (a & b) << 1;
    a = x;
    b = y;
  }

  return a;
}
posted @ 2016-07-10 16:11  信步闲庭、、  阅读(139)  评论(0编辑  收藏  举报