Topic:
As shown in title
Ideas:
Logical operations, binary operations, are not related to &, or |, non-, XOR, and shift >>,<<.
In addition, in decimal, only the bitwise add and carry two operations.
The same is true from the binary angle, where the bit bits are added together with the corresponding carry.
1, bit bits add, through the logical operation of the XOR operation can be achieved, such as 0+1=1,1+0=1,0+0=0;
2, carry operation, through the operation of the logical operation can be achieved, such as 1+1=1, because carry is toward the high +1, so need to move the result of the left one bit.
The addition operation of the above two operations is the result of the addition operation, which is a recursive process, which can also be realized by non-recursive loop.
For a+b, equivalent to (a^b) + (a&b) <<1
Code:
#include <iostream>using namespace std;//recursive methodint add_1 (int num1,int num2) { if (num1==0) return num2; if (num2==0) return NUM1; int num_xor=num1^num2; int carry= (num1&num2) <<1; Return Add_1 (Num_xor,carry);} Non-recursive methodint add_2 (int num1,int num2) { int sum=0; int num3=0; int num4=0; while (num1&num2) { num3=num1^num2; num4= (num1&num2) <<1; num1=num3; num2=num4; } sum=num1^num2; return sum;} int main () { int num1=100; int num2=200; cout << add_1 (num1,num2) << Endl; cout << add_2 (num1,num2) << Endl; return 0;}
(written question) The addition operation is only realized by logical operation