Here we implement suchAlgorithm: The addition, subtraction, multiplication, and Division operations are not used. Only bitwise operations are used to add and subtract integers.
Principle: The exclusive or operation also becomes a semi-addition. In essence, it does not bring in the addition of BITs, and the position where carry is needed can be obtained through the operation;
Adds the result of an exclusive or operation to the result after the operation with one left shift;
Through the repeated addition Process, and the calculation result will certainly be no more than 32 after this addition is zero (assuming that the int type occupies 32 bits), this can be used as a condition for the end of the loop.
Subtraction is implemented by converting to addition.
CodeAs follows:
# Include <stdio. h> int add (INT num_a, int num_ B); int sub (INT num_a, int num_ B); int main () {int A =-31; int B = 27; printf ("% d + % d = % d \ n", a, B, add (a, B )); printf ("% d-% d = % d \ n", A, B, sub (A, B); Return 0 ;}int add (INT num_a, int num_ B) {int temp_xor = 0; int temp_and = 0; // num_ B is used as the increment and the generated carry value will be saved later. As the loop continues, the carry value will definitely change to 0 while (num_ B) {// an exclusive or operation is equivalent to an addition without bits. The result is stored in temp_xor = num_a ^ num_ B; printf ("% d ^ % D = % d \ n ", num_a, num_ B, temp_xor); // calculates which locations will generate carry temp_and = num_a & num_ B; printf ("% d & % d = % d \ n", num_a, num_ B, temp_and); // use temp_xor as the new addition num_a = temp_xor; // shifts the left digit to the number of digits to be carried into the number of digits to be added. In this way, the sum of the non-incoming bits and the generated carry value num_ B = temp_and <1 ;}return temp_xor ;} int sub (INT num_a, int num_ B) {// convert subtraction to addition. bitwise inversion and addition can get the opposite number (the complement CODE OF A and the complement code of-A is 0) return add (num_a ,(~ Num_ B + 1 ));}