思路
方法:使用位运算实现二进制加法
Java实现
1 class Solution { 2 public int add(int a, int b) { 3 int sum, carry; 4 while(b != 0) //运算到没进位为止 5 { 6 sum = a ^ b; // 用异或运算求无进位和 7 carry = (a & b) << 1; 8 a = sum; 9 b = carry; 10 } 11 return a; 12 } 13 }
C++实现
注意:C++不支持负值左移!!
有2种解决方法:
(1) a&b的结果强转成unsigned int之后再左移。
1 class Solution { 2 public: 3 int add(int a, int b) 4 { 5 int sum, carry; 6 while(b != 0) //运算到没进位为止 7 { 8 sum = a ^ b; // 用异或运算求无进位和 9 carry = (unsigned int)(a & b) << 1; // C++不支持负值左移!!这里要加上unsigned int 10 a = sum; 11 b = carry; 12 } 13 return a; 14 } 15 };
(2) 用与 x 相与的方法人工去除最高位可能出现的 1, 之后再左移一位。
1 class Solution { 2 public int add(int a, int b) { 3 int x = ~(1 << 31); 4 int sum, carry; 5 while(b != 0) //运算到没进位为止 6 { 7 sum = a ^ b; // 用异或运算求无进位和 8 carry = (a & b & x) << 1; 9 a = sum; 10 b = carry; 11 } 12 return a; 13 } 14 }