【JZ65 Addition without addition, subtraction, multiplication and division】Problem solution

topic

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

Data range: Both numbers satisfy −10≤n≤1000
Advanced: Space complexity O(1), time complexity O(1)

Difficulty: Easy

Topic link: Addition without addition, subtraction, multiplication, and division

example

Enter 1,2

return value 3

the code 

int Add(int num1, int num2 ) {
    // write code here
    while(num2 != 0)//当不在进位时
    {
        int tmp = num1^num2;//通过每一次异或得到数值位
        num2 = (num1&num2)<<1;//进位 位
        num1 = tmp;//更新数值位
    }
    return num1;//返回两数之和
}

 answer

According to the topic, + - * / cannot be used to add two numbers, then we may think of &,|,^ these bit operators

The next solution is to use ^ and & to add two numbers. (If you are familiar with the principles of computer composition, you may think of the ALU adder in the cpu)

Usually we calculate the sum of two numbers, such as 1+ 2 = 3, and the corresponding binary digits are int four bytes of 32 bits. Here we show the last four digits first. 

0001 + 0010 = 0011 (here we will see that it is only the addition of values, and we will get the result we want, but let’s take a closer look, the adder in the cpu (which has both numerical calculations and carry calculations) ) )

So here we also implement both numerical calculations and carry calculations

First let num1 be the value bit, num2 is the carry bit, while (the carry bit), when the carry is not in, the calculation is complete (num2 is 0)

In the loop, we first use num1 and num2 to perform XOR operation (the same is 0, different is 1) to get the current value bit

Perform a bitwise AND with num1 and num2, and then shift left by 1 bit to complete the carry calculation

First look at the addition calculation

Next, look at the calculation in the code

Guess you like

Origin blog.csdn.net/qq_72505850/article/details/132493685