在 Java 中附加整数数组元素
问题描述:
我有一个数组,比如说
int a[]={2,0,1,0,1,1,0,2,1,1,1,0,1,0,1};
我需要附加 5 个相邻元素中的每一个,并将它们分配给一个新数组 b
,其中 length=(a.length/5);
并且我想附加 5 个相邻元素,以便我有:int b[]={20101,10211,10101};
我需要对各种长度的数组执行此操作,在大多数情况下 a
的长度大于 15.
I need to append each of the 5 neighboring elements and assign them to a new array b
with length=(a.length/5);
and i want to append the 5 neighboring elements so that I have:
int b[]={20101,10211,10101};
I need to do this for various length arrays, in most cases with length of a
being greater than 15.
任何帮助将不胜感激,我正在用 Java 编程.
Any help would be greatly appreciated, I'm programming in Java.
提前致谢.
答
非常简单:
// Assuming a.length % 5 == 0.
int[] b = new int[a.length / 5];
for (int i = 0; i < a.length; i += 5) {
b[i/5] = a[i]*10000 + a[i+1]*1000 + a[i+2]*100 + a[i+3]*10 + a[i+4];
}