## NVIDIA Interview Question Software Engineer / Developers

- 0of 0 votes
Given two numbers "a" and "b" and an average formula (a+b)/2. Find one condition where it wont work. Also, give solution to it

**Country:**United States

**Interview Type:**Phone Interview

Add "1" only when both end with a bit 1 (aka both are odd)

int computeAvg(int a, int b)

{

return (a >> 1 + b >> 1 + (a&b) &1);

}

suppose a and b are int....

and a and b = (2^31)-1;

so (a+b) will cause overflow and hence (a+b)/2 wnt work

so we need to use (a/2) + (b/2) keeping in mind if they are even or odd so that the fractional part is not lost....

1)

In case

a=0 (as 0 is also a number)

b=0

(a+b)/2 = 0/2 will be fail

sol: if both number are 0 result =0

-------------------------

2)

As average formula (a+b)/2 does not mention that return type is int or float

in case

int average (int a,int b)

{

return (a+b)/2 ;

}

for single odd numbers this function will be fail

-------------------------------

3)If

float average (int a,int b)

{

return (a+b)/2 ;

}

number out of range (a+b) is the only issue... for which sol is already mentioned above in the top.... (a/2 + b/2)

1)

In case

a=0 (as 0 is also a number)

b=0

(a+b)/2 = 0/2 will be fail

sol: if both number are 0 result =0

-------------------------

2)

As average formula (a+b)/2 does not mention that return type is int or float

in case

int average (int a,int b)

{

return (a+b)/2 ;

}

for single odd numbers this function will be fail

-------------------------------

3)If

float average (int a,int b)

{

return (a+b)/2 ;

}

number out of range (a+b) is the only issue... for which sol is already mentioned above in the top.... (a/2 + b/2)

1)

In case

a=0 (as 0 is also a number)

b=0

(a+b)/2 = 0/2 will be fail

sol: if both number are 0 result =0

-------------------------

2)

As average formula (a+b)/2 does not mention that return type is int or float

in case

int average (int a,int b)

{

return (a+b)/2 ;

}

for single odd numbers this function will be fail

-------------------------------

3)If

float average (int a,int b)

{

return (a+b)/2 ;

}

number out of range (a+b) is the only issue... for which sol is already mentioned above in the top.... (a/2 + b/2)

int avg = (a/2) + (b/2) + ((a%2 + b%2)/2)

- Anonymous on May 16, 2012 Edit | Flag Reply