Sword Finger - Simple - Addition without addition, subtraction, multiplication and division

Sword Finger - Simple - Addition without addition, subtraction, multiplication and division

Question description

Write a function to find the sum of two integers. It is required that the four arithmetic symbols +, -, *, / should not be used in the function body.

Ideas

(1) After the AND (&) operation is performed on two numbers, the binary system retains the same position of 1, which is the position that requires carry.
(2) After the XOR (^) operation is performed on two numbers, the binary digits retain the positions of 1 except for the same 1.
(3) The loop performs an XOR operation on the result of the carry after the AND (&) operation between the two numbers and the result of the XOR (^) operation on the two numbers.
(4) Until there is no position carry in binary, the operation is completed.

code

class Solution {
    
    
    public int add(int a, int b) {
    
    
        // 任何数 +0 都等于自身,一个数为 0 则直接返回另一个数。
        if (a == 0) {
    
    
            return b;
        }
        if (b == 0) {
    
    
            return a;
        }
        while (b != 0) {
    
    
            // 与运算得到两个数二进制都为 1 的部分,左位移进位。
            int temp = (a & b) << 1;
            // 异或运算得到两个数二进制不同时为 1 的 1 部分。
            a ^= b;
            // 将进位的数继续与 a 做运算,直到没有进位。
            b = temp;
        }
        return a;
    }
}

Guess you like

Origin blog.csdn.net/qq_32301683/article/details/108361935