算法题 A + B Problem

1.Write a function that add two numbers A and B. You should not use + or any arithmetic operators.

 

solution:

public class Solution {
    /**
     * @param a: An integer
     * @param b: An integer
     * @return: The sum of a and b
     */
    public int aplusb(int a, int b) {
        /**
         * a ^ b 二进制位数相同的结果为0,其他为1  ,所以结果为应该进位的地方没有进位
         * a & b 二进制位数都为1的结果为1,其他为0,所以结果为进位的地方都为1
         * (a & b) << 1 则为向左进一位,最后一位补0,结果为进位之后的结果
         * 所以直到b为0之前都会进行进位的计算 而b每次都会左移一位,最终肯定会为0
         */
        while (b != 0) {
            int _a = a ^ b;
            int _b = (a & b) << 1;
            a = _a;
            b = _b;
        }
        return a;
    }
}

 

posted @ 2018-05-07 18:08  月关莫利亚  阅读(225)  评论(0编辑  收藏  举报