不使用算数运算符 完成两数求和

来源:互联网 发布:淘宝怎么改会员名字 编辑:程序博客网 时间:2024/05/17 07:08
class Solution {    /*     * param a: The first integer     * param b: The second integer     * return: The sum of a and b     */    public int aplusb(int a, int b) {        // write your code here, try to do it without arithmetic operators.        if(b == 0){            return a;        }        int c = a ^ b;//a,b进行异或运算但是不进位        int d = (a & b) << 1;//a,b进行与运算(一假为假),得出哪里需要进位,通过左移运算进位        return aplusb(c,d);    }};

总结:
1、<<(左移运算符)的优先级大于 &(与运算)的优先级
2、此题通过if(b==0)来控制迭代的终止
3、如果异或运算能够不进位,那么异或运算相当于加法!!!,此题正是通过不断的循环使得异或运算能够不进位。

0 0
原创粉丝点击