We know that to implement addition we need to use arithmetic symbols, so how to implement addition without using arithmetic symbols? Today, the editor will introduce how to implement addition without using addition, subtraction, multiplication and division operators. You can refer to it if you need it.
Write a function to find the sum of two integers. It is required that the four arithmetic symbols " ", "-", "*" and "/" must not be used in the function body.
Example:
1 2 |
|
Tips:
a, b may be negative or 0, the result will not overflow the 32-bit integer
Solve the problem Idea 1
array_sum function
Code
1 2 3 4 5 6 7 8 9 10 11 |
|
Solution idea 2 - With the help of bit operations
this question bit It's better to memorize the operations. After all, the analog addition usage of bit operations is basically just this question, and it can be easily forgotten. . . . .
^ Or - equivalent to summation without carry, imagine the simulation situation in base 10: (for example: 19 1 = 20; sum without carry is 10, not 20; because it does not care Carry situation)
& and - are equivalent to finding the number of carries for each bit. First look at the definition: 1 & 1 = 1; 1 & 0 = 0; 0 & 0 = 0; that is, when both are 1 is only 1, which can just simulate the situation of the carry number, or imagine the simulation situation in base 10: (9 1 = 10, if it is processed with the idea of &, then the carry number obtained by 9 1 is 1, not 10, So use <<1 to move one position to the left, so it becomes 10);
The formula is: (a^b) ^ ((a&b)<<1) That is : Find the number of carries each time without carry - We need to repeat this process until the number of carries is 0;
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Problem-solving ideas 3 - Bit by bit calculation
The principle is equivalent to bit operation, but the implementation of manual bit operation
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
Recommended learning: php video tutorial
The above is the detailed content of How to implement addition in PHP without using addition, subtraction, multiplication and division symbols. For more information, please follow other related articles on the PHP Chinese website!