A+B问题:给出两个整数a和b,求他们的和,但不能使用+
等数学运算符.
注意事项:
1、A与B是32位整数
2、可使用位运算符
样例:如果 a=1
并且 b=2
,返回3
一、非递归
1 public class Solution { 2 /** 3 * @param a: An integer 4 * @param b: An integer 5 * @return: The sum of a and b 6 */ 7 public int aplusb(int a, int b) { 8 // write your code here 9 int c = 0,d = 0; 10 while((a&b) != 0){//a和b之间有进位 11 c = a^b; //忽略进位相加 12 d = (a&b)<<1;//应该进位的值 13 a = c; 14 b = d; 15 } 16 return a|b;//接返回两者|值 17 } 18 }
二、递归
1 public class Solution { 2 /** 3 * @param a: An integer 4 * @param b: An integer 5 * @return: The sum of a and b 6 */ 7 public int aplusb(int a, int b) { 8 // write your code here 9 if((a&b)==0) 10 return a|b;//接返回两者|值 11 else 12 return aplusb(a^b,(a&b)<<1); 13 } 14 }