将每2个元素组合成一个奇怪的数组,留下最后一个元素(Java)
下面是我尝试做的一个例子:
假设我有一个字符串数组,内容为{“a”、“b”、“c”、“d”、“e”} 和第二个数组,其内容为{“f”、“g”、“h”、“i”} 我想要在第一个数组上返回{“ab”、“cd”、“e”},在第二个数组上返回{“fg”、“hi”}的代码。我正在使用Java。下面是我写的不起作用的代码
int val;
if ((ciphertextVals.length % 2) == 0)
val = ciphertextVals.length/2;
else
val = ciphertextVals.length/2 + 1;
String[] encryptedBinary = new String[val];
for (int i = 0; i <= ciphertextVals.length-1; i+=2)
{
String bin1 = Integer.toBinaryString(ciphertextVals[i]);
String result;
if (i == ciphertextVals.length-1)
{
result = bin1;
}
else
{
String bin2 = Integer.toBinaryString(ciphertextVals[i+1]);
result = bin1 + bin2;
}
encryptedBinary[i/2+1] = result;
}
# 1 楼答案
像这样的方法应该会奏效:
# 2 楼答案
实际上,您正在使逻辑变得复杂,这不是必需的
你所说的可以写成这样的代码:
要检查它是否工作,让我们用
Integer.toString(ciphertextVals[i])
替换Integer.toBinaryString(ciphertextVals[i])
,并打印encryptedBinary
的所有元素