371. Sum of Two Integers

来源:互联网 发布:大学软件测试专业 编辑:程序博客网 时间:2024/06/09 20:18

Calculate the sum of twointegers a and b, but you are not allowed to use the operator + and -.

Example:

Given a = 1 and b = 2, return3.

    谷歌翻译:计算两个整数ab的和,但不允许使用运算符+ -

    例:

     给定a = 1b = 2,返回3

    这题比较简单,可能是以前我以前做过类似的题目,所以说其实算法题大家多练习,多思考,还是可以提高的。贵在坚持。学习汇编的,应该能够很快了解它。代码如下:

非递归代码:

public class Solution {

    public int getSum(int a, int b) {

                 int c=a^b;

                 int d=a&b;

                 while(d!=0){

                      d=d<<1;

                      a=c;

                      c=a^d;

                      d=a&d;

                 }

                 return c;

    }

}

我做一本习题时,一种递归算法:

public class Solution {

    public int getSum(int a, int b) {

                 if(b==0) return a;//没有进位的时候完成运算

                 int sum ,carry;

                 sum=a^b;//完成第一步没有进位的加法运算

                 carry=(a&b)<<1;//完成第二步进位并且左移运算

                 return getSum(sum,carry);//进行递归,相加

           }

}

 

0 0
原创粉丝点击