Guess you have to add two integers or numbers but without using the arithmetic operator. You cannot use any arithmetic operator like +, -, ++, --, ... etc. How will you do that? This question was asked in Microsoft Online Assessment.
For solving this problem we have to go back to our Digital Electronics concepts where for adding two bits, we can do the XOR(^) of those bits. if they have a carry, we can find that out by applying AND(&) of them. So, this is the simple concept of Half Adder which is used to add 2 single bits.
Input: 3 5
Output: 8
C++ code for this problem:
Explanation:
Input: 3 5
For x=3 and y=5:
Loop1: y = 5 != 0,
carry = 3 & 5 = 1,
x = 3 ^ 5 = 6,
y = 2.
Loop2: y = 2 != 0,
carry = 6 & 2 = 2,
x = 6 ^ 2 = 4,
y = 4.
Loop3: y= 4!=0,
carry = 4 & 4 = 4,
x = 4 ^ 4 = 0,
y = 8.
Loop4: y = 8 != 0,
carry = 8 & 0 = 0,
x = 0 ^ 8 = 8,
y = 0.
As y==0 then the loop will end and the answer will be x which equals 8.
Output: 9
If you have any questions, ask them in the comments.
Comments
Post a Comment