Of course you can just return a + b to get accepted. But Can you challenge not do it like that?(You should not use + or any arithmetic operators.)
I encountered such a problem when I did the algorithm question today.
Although it’s not too difficult, this question is quite interesting.
Write a function that add two numbers A and B.
Are a and b both
Can I use bit operation?
- Sure you can.
Of course you can just return a + b to get accepted. But Can you challenge not do it like that?(You should not use
+ or any arithmetic operators.)
If we can’t use
+ or any arithmetic operators, we can only use bit operation.
So, we need to understand how the half adder works.
The half adder adds two single binary digits A and B. It has two outputs, sum (S) and carry (C). The carry signal represents an overflow into the next digit of a multi-digit addition. The value of the sum is 2C + S. The simplest half-adder design, pictured on the right, incorporates an XOR gate for S and an AND gate for C.
Here is the Half adder in action:
The Boolean logic for the sum (in this case S) will be A′B + AB′ whereas for the carry (C) will be AB. With the addition of an OR gate to combine their carry outputs, two half adders can be combined to make a full adder. The half adder adds two input bits and generates a carry and sum, which are the two outputs of a half adder. The input variables of a half adder are called the augend and addend bits. The output variables are the sum and carry. The truth table for the half adder is:
Before beginning, let’s divide the decimal A=9 and B=7 into binary A=1001, B=0111.
First calculate the number of digits (not carry):
1001 + 0111 = 1110
The result is the same as A^B (A XOR B).
Then get the carry.
If 1001 + 0111 do the carry, the carry will occur only when 1 + 1 is there.So, how do we get the carry signal? 1 + 0, 0 + 0, 0 + 1 will not have a carry signal, it satisfies the truth table of phase and &. We can also see directly from the inside of the half adder , S = A ^ B, C = A & B.
Plus the carry.
We find that the carry signal appears at 1 + 1 (1&1 = 1), and the previous bit needs to be entered. That is, C can be further expressed as C = (A & B) << 1.
repeat and repeat.
Since if the previous bit 0+1 plus the carry symbol 1, it will also be carried. It is necessary to repeat the above process continuously.
Here I will use the Swift.