Algorithm Problem 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 with the same number of bits, the result is 0, the others are 1, so the result is that there is no carry where it should be.
         * a & b binary digits are all 1, the result is 1, the other is 0, so the result is 1 where the carry is
         * (a & b) << 1 is to carry one bit to the left, the last bit is filled with 0, and the result is the result after the carry
         * So the carry calculation will be performed until b is 0, and b will be shifted to the left by one bit each time, and it will definitely be 0 in the end
         */
        while (b != 0) {
            int _a = a ^ b;
            int _b = (a & b) << 1;
            a = _a;
            b = _b;
        }
        return a;
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325687526&siteId=291194637