Sword refers to offer—65. Addition without addition, subtraction, multiplication and division—analysis and code (Java)

Sword refers to offer-65. Do not add, subtract, multiply and divide for addition-analysis and code [Java]

1. Title

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

Two, analysis and code

1. Binary operations

(1) Thinking

Converting two integers to binary processing can replace the four arithmetic operations required by bit operations. The specific steps include:
1) XOR the numbers on each bit, that is, add directly, without considering the carry;
2) Perform AND processing on the numbers on each bit, that is, consider the carry;
3) Use the numbers obtained in the first two steps The above method continues to add until no carry is generated.

(2) Code

public class Solution {
    
    
    public int Add(int num1,int num2) {
    
    
        int sum = num1 ^ num2;
        int carryBit = (num1 & num2) << 1;
        while (carryBit != 0) {
    
    
            int preSum = sum;
            sum = preSum ^ carryBit;
            carryBit = (preSum & carryBit) << 1;
        }
        return sum;
    }
}

(3) Results

Running time: 9 ms, memory usage: 9376 k.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/112206523