VampishWolf
VampishWolf

Reputation: 11

How to get any numbers sorted from string variable in Java?

How to get any number like '101010' or '001101' to '111000' in Java? Following is the code to be used for and edited to attain the output

I tried putting the main logic and assigning values to line2 for output. I used line to fetch input, but it doesn't work!

/*NOTE : Class Name should be Main */
import java.io.*;
import java.util.*;
class Main {
    public static void main(String[] args) throws InterruptedException {
        List<String> inputByLine = new ArrayList<String>();
        try {
            // Get the object of DataInputStream
            InputStreamReader isr = new InputStreamReader(System.in,"UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            while ((line = br.readLine()) != null){
                inputByLine.add(line.toString());
            }
            for (String line2 : inputByLine)
                System.out.println(line2);
            isr.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

I expect the numbers to be sorted, all the ones to be on the beginning followed by the zeroes.

Upvotes: 1

Views: 654

Answers (3)

Marc ABOUCHACRA
Marc ABOUCHACRA

Reputation: 3463

public String sort(String input) {
    char tempArray[] = input.toCharArray();
    Arrays.sort(tempArray);
    String sortedString = String.valueOf(tempArray); //here the string is sorted "naturrally" with the 0 leading

    //You need to reverse it
    return new StringBuilder(sortedString).reverse().toString();
}

Another option is to implement your own Comparator and use it directly.
Hope this helps !

Upvotes: 0

Neel Patel
Neel Patel

Reputation: 143

As I have understood, you can count the number of 1's and 0's and according sort them into your final string. (Assuming you are taking only binary numbers as strings - only 1's and 0's).

    String numbers="111000111000",result="";
    StringBuilder sb= new StringBuilder();
    int count_1=0,count_0=0;
    for(int i=0;i<numbers.length();i++){
        if(numbers.charAt(i)=='1'){
            count_1++;
        }    
        else if(numbers.charAt(i)=='0'){
            count_0++;
        }
    }
    for(int i=0;i<count_1;i++)  
        sb.append("1");
    for(int i=0;i<count_0;i++)
        sb.append("0");
    result=sb.toString();

If you want to consider other cases too (for example you want to ignore strings if users type decimal numbers or anything) then you can add this line to your code

result=(sb.length()==0)?numbers:sb.toString();

Here, I have checked whether the StringBuilder is null or not and If it is null that means input doesn't contain only 1's and 0's.

Upvotes: 2

Alejandroppir
Alejandroppir

Reputation: 126

String numbers = "0110101";
char[] digits = numbers.toCharArray(); 
Arrays.sort(digits);
String result = new String(digits);

Upvotes: 0

Related Questions