gpt4 book ai didi

java - 如何从Java中的字符串变量中获取排序后的数字?

转载 作者:行者123 更新时间:2023-11-30 01:50:42 25 4
gpt4 key购买 nike

如何在 Java 中获取“101010”或“001101”到“111000”等任何数字?以下是要使用和编辑以获得输出的代码

我尝试将主要逻辑并赋值给 line2 以进行输出。我使用 line 来获取输入,但它不起作用!

/*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();
}
}
}

我希望对数字进行排序,所有数字都在开头,后跟零。

最佳答案

据我了解,您可以计算 1 和 0 的数量,然后将它们排序到最终的字符串中。 (假设您仅将二进制数作为字符串 - 仅 1 和 0)。

    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();

如果您也想考虑其他情况(例如,如果用户输入十进制数字或任何内容,您想忽略字符串),那么您可以将此行添加到您的代码中

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

在这里,我检查了 StringBuilder 是否为 null,如果为 null,则意味着输入不仅仅包含 1 和 0。

关于java - 如何从Java中的字符串变量中获取排序后的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56157179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com