"Sword Finger Offer"-48, do not add, subtract, multiply and divide for addition

1. Knowledge points of this question

Bit operation

2. Title description

Write a function to find the sum of two integers. The four arithmetic symbols +, -, *, / must not be used in the function body.

3. Problem solving ideas

Suppose the binary form of two digits a, b, the sum s = a + b, and a(i) represents the i-th bit of a in the binary system, then it can be divided into the following four cases:

a(i) b(i) No carry carry
0 0 0 0
0 1 1 0
1 0 1 0
1 1 0 1

It is observed that the sum operation without carry is the bitwise XOR result, and the carry is the result of the AND operation but needs to be shifted one bit to the left because the carry affects the operation of the next bit. So s = a + b is actually the result of no carry and + carry.

algorithm design:

  1. Find the sum without carry num1 ^ num2
  2. Find the carry (num1 & num2) << 1
  3. Determine whether the carry is equal to 0
    1. Equal to 0, indicating that the result of a+b at this time is equal to the sum without carry, and the sum without carry is returned directly
    2. Not equal to 0, it means that the result of a+b is equal to no carry and + carry, recursive function

4. Code

public class Solution {
    
    
    public int Add(int num1, int num2) {
    
    
        int noCarrySum = num1 ^ num2;
        int carry = (num1 & num2) << 1;
        return carry == 0 ? noCarrySum : Add(noCarrySum, carry);
    }
}

Guess you like

Origin blog.csdn.net/bm1998/article/details/113887465