To prove safety: Do not do addition and subtraction, multiplication and division

Title Description

A write function, and the sum of two integers, the function may not be used in vivo requires +, -, ×, ÷ four operational sign.

Sample

输入:num1 = 1 , num2 = 2

输出:3

solution

Number of two first XORed result is not obtained by the addition of a carry. The number of two for recycling bitwise AND, and a left, until the carry is 0.

 

public  class Solution {
     public  int the Add ( int num1, int num2) {
         the while (num2 = 0! ) {
             int T = num1 ^ num2; // do not carry the addition 
            num2 = (num1 & num2) <<. 1; // calculate the carry value 
            = num1 T; 
        } 
        return num1; 
    } 
}

 

Detailed ideas:

Example: 5 + 7

How to do is look at the decimal: three steps

  1. Adding to the bit values, not carry, to give 2.
  2. Carry value is calculated, this step to give 10. If the carry is 0, then the value from the first step is the final result.
  3. Repeating the above two steps, but the added value becomes a result of the two steps 10 and 2 obtained, to give 12.

Similarly, we can use a three-step way to calculate the sum of the binary value:

        5->101,7->111

  1. Adding to the bit values, not binary, the binary equivalent of each sum you XOR operation, 101 ^ 111 , to give 010
  2. Calculated carry value corresponds you do the operation to give 101, left again to give a 1010 (101 & 111) << 1 , to obtain 1010
  3. Repeating the above two steps, you are added 010 ^ 1010 = 1000 , the carry is 100 = (010 & 1010) << 1 . Continue repeating the above two steps: 1000 ^ 100 = 1100, the carry is 0, out of the loop 1100 as the final result.

 

Guess you like

Origin www.cnblogs.com/lisen10/p/11345206.html