Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add two numbers without using + operator in C using bit manipulation

I recently came across this interview question and I'm not good in bit manipulation. Can you guys explain what the function 'f' does. I'm not sure what this recursive function does.

unsigned int f (unsigned int a , unsigned int b)
{
   return a ?   f ( (a&b) << 1, a ^b) : b;
}

I tried to paste the code in Visual Studio to test the logic but compiler is throwing some error message "cannot implicitly convert type 'uint' to 'bool'. Is the condition statement (a ?) in the return missing something? but I'm sure the interview question was exactly same as mentioned above

like image 410
karthickeyan Avatar asked Oct 03 '22 12:10

karthickeyan


1 Answers

Well already a few people in the comments mentioning this just adds two numbers. I'm not sure of a better way to figure that out than just try some inputs and note the results.

Ex:

f(5,1) --> returns f(2,4) --> returns f(0,6) --> returns 6

 1.) 5&1 = 1 bit shifted = 2:  5^1 = 4
 2.) 2&4 = 0 bit shifted = 0:  2^4 = 6
 3.) a = 0 so return b of 6

f(4,3) --> returns f(0,7) --> returns 7

1.) 4&3 = 0 bit shifted = 0:  4^3 = 7
2.) a = 0 so return b of 7

After you show a few examples of the output I suppose you could postulate f returns the two inputs added together.

like image 197
Kevin DiTraglia Avatar answered Oct 13 '22 11:10

Kevin DiTraglia