Find integer average of 2 integers | PROGRAMMING INTERVIEWS
The definition of integer average is the highest smaller integer if average is floating point number. Also the condition if that they can not use any typecasting or any datatype other than int.
Example:
a = 4, b = 5, avg = 4
a = 4, b = 6, avg = 5
a = -4, b = -6, avg = -5
a = 4, b = -5, avg = -1
a = -4, b = -5, avg = -5
The definition of integer average is the highest smaller integer if average is floating point number. Also the condition if that they can not use any typecasting or any datatype other than int.
Example:
a = 4, b = 5, avg = 4
a = 4, b = 6, avg = 5
a = -4, b = -6, avg = -5
a = 4, b = -5, avg = -1
a = -4, b = -5, avg = -5
- int get_average (int a, int b)
- {
- int a_half = a/2;
- int b_half = b/2;
- bool a_even = a%2==0? true:false;
- bool b_even = b%2==0? true:false;
- if (a>=0 && b>=0)
- {
- if (!a_even && !b_even)
- return a_half + b_half + 1;
- return a_half + b_half;
- }
- else if (a<0 && b<0)
- {
- if (a_even && b_even)
- return a_half + b_half;
- return a_half + b_half - 1;
- }
- else
- {
- int sum = a+b;
- if (sum < 0 && sum%2 != 0)
- return sum/2 - 1;
- return sum/2;
- }