Pergunta de entrevista da empresa NVIDIA

Given two numbers a and b, we have an averaging function (a+b)/2. This function wont work under certain cases. I was supposed to tell the case, and also how to handle it.

Respostas da entrevista

Sigiloso

18 de mai. de 2012

When a and b will be very large values, we would have an overflow. Hence we need to right shift a and b first , i.e a/2 and b/2 , and then add them. However, this wont work if both a and b are odd numbers. In case, if both are odd, then we need to add 1 to the final result eg : a = 5 = 101 b = 3 = 011 ( a >> 1)+ (b >> 1) = 3 . So we add 1 to it. Hence, answer is 4

19

Sigiloso

22 de out. de 2015

Won't work if a and b are very large values. We could do this instead: a + (b - a) / 2 or b + (a - b) / 2, depending on which one is greater.

3