This code takes a list of ints and sums their pairs, storing the summed pairs in an array sumPairs
, then returning that array. If the supplied array toSum
has an odd number of elements, it returns the sumPairs
with the last element of the toSum
as the last element of sumPairs
. Any suggestions for improving my code, or accomplishing this task in a better way, would be most appreciated!
public static int[] collapse(int[] toSum) {
int[] sumPairs = new int[toSum.length / 2 + toSum.length % 2];
for (int i = 0, j = 0; i < toSum.length - 1; i+=2, j++) {
sumPairs[j] = toSum[i] + toSum[i + 1];
}
if (toSum.length % 2 == 1 && sumPairs[sumPairs.length - 1] == 0) {
sumPairs[sumPairs.length - 1] = toSum[toSum.length - 1];
}
return sumPairs;
}