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:
If the input array is: 2 3 7 10
The binary string array will be:
10
11
111
1010
But I want the output array to be like the following:
0010
0011
0111
1010
#2
If the input array is: 2 10 20
The binary string array will be:
10
1010
10100
But I want the output array to be like the following:
00010
01010
10100
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]);
}
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With