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.
Problem
Description
Write a function that add two numbers A and B.
Are a and b both 32bit
integers?
 Yes.
Can I use bit operation?
 Sure you can.
Sample


challenge
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.)
Answer
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.
Half adder
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 multidigit addition. The value of the sum is 2C + S. The simplest halfadder 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.[1] 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:
Conversion
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.
Code
Here I will use the Swift.

