Finding the middle element(s) of an array in Java

前端 未结 7 1878
小蘑菇
小蘑菇 2021-02-14 13:03

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

相关标签:
7条回答
  • 2021-02-14 14:07

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题