Given an array of integers, I need to return a new array containing the middle element(s) from the original array. Specifically, the result will have one element if the length o
start + (end - start) / 2
is prefered over (start + end) / 2
. In case of using (start + end) / 2
and the summation result of start + end is larger than the integer max value, this will cause overflow.
public class MidOfArray {
static final int start = Integer.MAX_VALUE;
static final int end = Integer.MAX_VALUE;
public static void doesnotWork() {
int mid = (start + end) / 2;
System.out.println(mid); // output: -1
}
public static void worksGreat() {
int mid = start + ((end + start) / 2);
System.out.println(mid); // output: 2147483646
}
public static void main(String[] args) {
doesnotWork();
worksGreat();
}
}