Search code examples
javabinarypad

Add zeros to the left of binary string - Java


Can you please help me find a way to add zero's to the left of a binary string, here's what I thought would work but it just prints the binary without 0's.

package flipping_bits;
import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    int cases = input.nextInt();        //Número de casos

    int[] dec_nums=new int[cases];      //Arreglo contenedor de casos
    for (int i=0;i<cases;i++){
        dec_nums[i]=input.nextInt();    //Almacenamiento de casos
    }

    int[] bin_nums=new int[cases];  //Arreglo con dec-bin
    for (int i=0;i<cases;i++){              
        bin_nums[i]=Integer.parseInt(String.format("%032d",(Integer.parseInt(Integer.toBinaryString(dec_nums[i]))))); //Convertir cada decimal en el arreglo a binario
    }


    //Imprimir binarios
    for (int i=0; i<cases;i++){
        System.out.println(bin_nums[i]);
    }

}
}

Solution

  • If I understand your question correctly, just change bin_nums from an int[] to a String[] and don't parse the integer that you formatted, you will end up with a 32 bit representation of an integer

    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
    
        int cases = input.nextInt();        //Número de casos
    
        int[] dec_nums=new int[cases];      //Arreglo contenedor de casos
        for (int i=0;i<cases;i++){
            dec_nums[i]=input.nextInt();    //Almacenamiento de casos
        }
    
        String[] bin_nums=new String[cases];  //Arreglo con dec-bin
        for (int i=0;i<cases;i++){              
            bin_nums[i]=(String.format("%032d",(Integer.parseInt(Integer.toBinaryString(dec_nums[i]))))); //Convertir cada decimal en el arreglo a binario
        }
    
    
        //Imprimir binarios
        for (int i=0; i<cases;i++){
            System.out.println(bin_nums[i]);
        }
    
    }
    

    This is my test case with the result:

    3
    1
    2
    3
    00000000000000000000000000000001
    00000000000000000000000000000010
    00000000000000000000000000000011
    

    But assuming you might be trying to solve some algorithm question which usually needs you to solve it in an optimal way, this might not do the trick and may exceed the time limit.

    It seems like an exercise because of the class named Solution and the style of the code , eg: test-case, number of test cases ...