[Sword refers to Offer learning] [interview question 47: addition without subtraction, multiplication, division], sword refers to offer
Question: To write a function and calculate the sum of two integers, The +,-, ×, and limit operators must not be used in the function.Solutions
The binary value of 5 is 101, and the binary value of 17 is 10001. We still try to divide the calculation into three steps: the first step is to add but not to carry the result. The result is 10100 (the last two digits are 1, and the result of the addition is 10 of binary. This step is not carried, so the result is still 0. Step 2 Write down the carry. In this example, only a carry is generated when the last bit is added, and the result is 10 of the binary. The third step adds the results of the first two steps. The result is 10110, Which is exactly 22 in decimal format. It can be seen that the three-step strategy is also applicable to binary.
Next, we try to replace the binary addition with bitwise operations. The first step does not consider adding the carry to each bit. 0 plus 0, 1 plus 1 results are 0. 0 plus 1, 1 plus 0 results are 1. We have noticed that this is the same as or. For an exclusive or, 0 and 0, 1 and 1 exclusive or result is 0, while 0 and 1, 1 and 0 exclusive or result is 1. Next, we will consider the second step. For Addition of 0, 0 plus 1, and 1 plus 0, there will be no carry. Only when 1 plus 1, there will be a carry forward. In this case, we can think of two numbers first performing bitwise AND operations, and then moving one digit to the left. When the two numbers are both 1, the result of bitwise AND is 1, and the rest are 0. Step 3: add the results of the first two steps. The process of adding step 3 is to repeat the previous two steps until there is no carry.
Algorithm Implementation
Public class Test47 {public static int add (int x, int y) {int sum; int carry; do {sum = x ^ y; // one digit of x & y is 1, indicating that it is the carry of the previous digit, so moving one carry = (x & y) to the left <1; x = sum; y = carry;} while (y! = 0); return x;} public static void main (String [] args) {System. out. println (add (1, 2) + "," + (1 + 2); System. out. println (add (13, 34) + "," + (13 + 34); System. out. println (add (19, 85) + "," + (19 + 95); System. out. println (add (865,245) + "," + (865 + 245 ));}}
Running result
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.