A + B问题

问题描述:给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。

1.A^B为不进位的相加结果。

2.(A&B)<<1为进位的位置。

重复上述两部直到不需要进位为止

Java代码有递归和非递归两种

递归的代码为

 1 public int aplusb(int a, int b) {
 2         // write your code here
 3         if(b == 0){
 4             return a; 
 5         }
 6         
 7         int sum = a^b;
 8         int evl = (a&b)<<1;
 9         return aplusb(sum, evl);
10         
11     }

总耗时1468ms。

 

非递归代码

 1 public int aplusb(int a, int b) {
 2         // write your code here
 3         int sum = a;
 4         while(b != 0){
 5             sum = a^b;
 6             b = (a&b)<<1;
 7             a = sum;
 8         }
 9         return sum;
10         
11     }

总耗时909ms。

posted on 2018-04-15 18:57  truman_zhn  阅读(157)  评论(0)    收藏  举报