Find integer Average of 2 integers.

• 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

• Check if both the integers are odd or even. If they are, then just find A+B/2. If not find the bigger number and reduce its value be 1 and find the average. i.e.If B > A average = A+(B-1)/2 else (A-1)+B/2.

• Isn't this as simple as this? or am I missing something ?
int averrage(int a, int b)
{
if((a+b) > 0)
return (a+b)/2;
else
return (a + b)/2 - 1;
}

• Why are you finding out the bigger number? Its not important. Answer by Irfan is correct.

• /**

• The definition of integer average is the highest smaller integer if average

• is floating point number. Also the condition is that they can not use any

• type casting or any data type 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

• @author shivam.maharshi
*/
public class IntegerAverage {

public static int average(int a, int b) {
int sum = a + b;
if(sum < 0 && sum%2==-1)
return (sum / 2) - 1;
else
return sum/2;
}

public static void main(String[] args) {
System.out.println(average(2, 3));
System.out.println(average(2, -6));
System.out.println(average(-5, -2));
System.out.println(average(-6, 7));
}

}

• @shivam.maharshi
We dont need to check if (sum < 0 && sum%2==-1)
Only if(sum%2==-1) is enough . As to get remainder as -1, sum has to be negative number only

• Answer by shivam is correct.
irfan's answer ignore the (sum < 0 && sum%2==-1) situation. if a = -4 and b = -6, the right answer is -5 not (a + b) /2 -1
And -5 % 2 == 1 not -1. :)

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.