英文:
How do I convert an array of integers to binary?
问题
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
String[] bin = new String[n];
for (int i = 0; i < n; i++) {
bin[i] = Integer.toBinaryString(arr[i]);
}
上述代码将整数数组转换为一个字符串数组(包含输入整数的二进制格式),但有一个注意事项。
例如:
如果输入数组为:2 3 7 10
二进制字符串数组将为:
10
11
111
1010
但我希望输出数组如下所示:
0010
0011
0111
1010
#2
如果输入数组为:2 10 20
二进制字符串数组将为:
10
1010
10100
但我希望输出数组如下所示:
00010
01010
10100
<details>
<summary>英文:</summary>
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
String[] bin = new String[n];
for (int i = 0; i < n; i++) {
bin[i] = Integer.toBinaryString(arr[i]);
}
The above code will convert the the whole array of integers into an array of `String`s (containing binary format of the input string), but there is a caveat.
For Example:
<br/>
If the input array is: 2 3 7 10<br/>
The binary string array will be:
10<br/>
11<br/>
111<br/>
1010<br/>
But I want the output array to be like the following:<br/>
0010<br/>
0011<br/>
0111<br/>
1010<br/>
#2<br/>
If the input array is: 2 10 20<br/>
The binary string array will be:<br/>
10<br/>
1010<br/>
10100<br/>
But I want the output array to be like the following:<br/>
00010<br/>
01010<br/>
10100<br/>
</details>
# 答案1
**得分**: 4
要使所有二进制字符串的长度与最长“字符串”的长度匹配,您可以首先找到最长的长度,然后使用 `String#format` 和 `String#replace` 进行零填充。
```java
int maxLen = 0;
for (int i = 0; i < n; i++) {
bin[i] = Integer.toBinaryString(arr[i]);
maxLen = Math.max(maxLen, bin[i].length());
}
for (int i = 0; i < n; i++) {
if (bin[i].length() != maxLen)
bin[i] = String.format("%" + maxLen + "s", bin[i]).replace(' ', '0');
System.out.println(bin[i]);
}
英文:
To have all of the binary strings match the length of the longest String
, you can first find the longest length and then use String#format
and String#replace
to pad with zeroes.
int maxLen = 0;
for (int i = 0; i < n; i++) {
bin[i] = Integer.toBinaryString(arr[i]);
maxLen = Math.max(maxLen, bin[i].length());
}
for (int i = 0; i < n; i++) {
if (bin[i].length() != maxLen)
bin[i] = String.format("%" + maxLen + "s", bin[i]).replace(' ', '0');
System.out.println(bin[i]);
}
答案2
得分: 1
你可以首先计算数组的最大二进制字符串长度,然后使用 Collections.nCopies
在每个二进制字符串表示之前添加所需的额外的 0
。
int mx = 0;
for (int i = 0; i < n; i++) {
bin[i] = Integer.toBinaryString(arr[i]);
mx = Math.max(mx, bin[i].length());
}
for (int i = 0; i < n; i++) {
bin[i] = String.join("", Collections.nCopies(mx - bin[i].length(), "0")) + bin[i];
}
英文:
You can first calculate the max binary string length of array then use Collections.nCopies
to add extra 0
needed before string representation of binary string each.
int mx = 0;
for (int i = 0; i < n; i++) {
bin[i] = Integer.toBinaryString(arr[i]);
mx = Math.max(mx, bin[i].length());
}
for (int i = 0; i < n; i++) {
bin[i] = String.join("", Collections.nCopies(mx - bin[i].length(), "0")) + bin[i];
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论