Editor:
do not realize addition and subtraction plus and minus signs
Today, there are a group of friends made a problem, requiring no plus and minus signs (including negative numbers) to achieve addition and subtraction.
Analyze
Look at the simplest case, assuming 1 + 1, in binary count, then the result is 10, can be seen from right to left becomes 0 in the first bit, the second bit becomes 1 due to rounding.
A value of the four kinds, 0 + 0 = 0 + 0 = 0 + 1 = 1 + 1 = 0, which fits the "exclusive or" situation.
Value of the second bit from the first bit of the carry plus the value itself, into the case also has four bits, 0 + 0 = 0 + 0 = 0,0 + 1 = 0 + 1 = 1, which It fits the situation "and" the.
General considerations, a + b is equivalent to a ^ b + (a & b ) << 1, which is an addition, recursion may be solved, when the feed outlet is 0 bit time.
Look at an example:
11 + 2
into binary, apply the above formula Analysis:
1011 + 0010
= 1001 + 0100
= 1101 + 0000
= 1101
The results Switch 10 is 13 hex
可以自己在草稿纸上多看看例子观察下。
所以Java代码实现如下:
public static int add(int a, int b){
return b == 0 ? a : add(a ^ b ,(a & b) << 1);
}
So how do subtraction it? Well represented adder subtractor can also be used, such as ab is equal to a + (- b), but not a negative number, we know that the Java integer value to complement coding, so a negative number corresponds to the number of "plus negated 1 ", so the code is as follows:
public static int sub(int a, int b){
return add(a, add(~b, 1));
}
这是群友给的答案,有点意思,记录一下。