Series 38 wins the offer: Do not do addition and subtraction, multiplication and division

The main thing to remember: For a digital arithmetic addition, multiplication and division plus minus than is bit computing. Bitwise XOR includes non. And see how to add two numbers into a bit operation. Because computers are binary, so think in binary thinking. Divided into two parts, namely: no carry bit for addition operations corresponding to the exclusive OR: 0 is the same, different 1; for the carry to bit, i.e. one two, can be seen with a left after bit. The above two methods, respectively, and said adder adding operation requires a carry bit how to handle two binary numbers are not. The final step is to add up the results of two steps above. Note that the third part is equal to invoke operations plus add their own operating functions. So to use recursion.

. 1  class Solution {
 2  public :
 . 3      int the Add ( int num1, int num2)
 . 4      {
 . 5          IF (num1 == 0 ) // Note that the special data write processing 
. 6              return num2;
 . 7          IF (num2 == 0 )
 . 8              return num1;
 . 9          int TEM ^ = num1 num2; // Step: XORed two numbers, the carry for the bits not required are added 
10          IF (num1 num2 & == 0 ) // recursive termination condition 
. 11              return TEM;
12 is          the else 
13 is          {
 14              int TEM2 = (& num1 num2) << . 1 ; // Step: two numbers for a left after the operation, the need for adding the carry bit 
15              return the Add (TEM, TEM2); // third step: adding the results of the first two, calls itself recursively 
16          }
 17      }
 18 };

 

Guess you like

Origin www.cnblogs.com/neverland0718/p/11230680.html