public class LeftSumRight_END {
public static void main(String[] args) {
/*
1 2 3 4 5 6 7 1 7, 2 6, 3 5, 4 : 8+8+8+4
0 1 2 3 4 5 6 7 0 7, 1 6, 2 5, 3 4 : 7+7+7+7
1 2 3 4 5 6 1 6, 2 5, 3 4 : 7+7+7
0 1 2 3 4 5 6 0 6, 1 5, 2 4, 3 : 6+6+6+3
数字必须从小到大进行排列;如果是偶数个则无需算中间数;如果是奇数个则需要算中间数
如果0开头,则前后累加和为最后一个数;如果1开头,则前后累加和为最后一个数加1
*/
int num[] = {1,2,3,4,5,6,7};
int sum = 0;
if(num[0] == 0) {
int num2[] = Arrays.copyOf(num, num.length-1);
System.arraycopy(num, 1, num2, 0, num.length-1);
sum = sumNum(num2);
} else {
sum = sumNum(num);
}
System.out.println("数组元素最后相加的结果是:"+sum);
}
// 进行前后相加的方法
static int sumNum(int num[]) {
int sum = 0;
int lenght = num.length;
int mid = lenght / 2;
if(lenght % 2 == 0) {
sum = mid * (num[lenght-1]+1);
} else {
sum = mid * (num[lenght-1]+1) + num[mid];
}
return sum;
}
}
"1+2+3+4+...+100" = 5050
最新推荐文章于 2024-06-05 15:24:20 发布