5
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 Strings (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

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Rashid Raza
  • 53
  • 1
  • 8
  • What exactly is your criteria for conversion? – Unmitigated Aug 15 '20 at 14:33
  • Why do you want to add more 0 zeros if the ones provided by the method represent the same number? Also, as @hev1 is asking, the criteria you show is not consistent. – JeroSquartini Aug 15 '20 at 14:34
  • Use same number of bits for all integers. If needed add zeroes in the front. If the largest number is 15, then minimum number of bits required to represent 15 is 4. Hence all the other number should be 4 bits. @hev1 – Rashid Raza Aug 15 '20 at 14:39
  • @RashidRaza I have added an answer. Is it what you want? – Unmitigated Aug 15 '20 at 14:41

2 Answers2

4

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]);
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

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];
}
Eklavya
  • 17,618
  • 4
  • 28
  • 57