猿问

字符串的二进制加法

我需要组合一个字符串数组,如下所示(因此结果字符串中的每个字符都是输入字符串中字符的按位 & )


String a = "10110001"

String b = "01101101"

String c = "10101011"


String result = "00100001"

我想出的解决方案:


long resultLong = 0;


for( String a : inputs )

{

    resultLong = resultLong & Long.parseLong( a ,2);

}


String result = Long.toBinaryString( resultLong );

输入字符串中的字符数可能非常长,并且上述解决方案不起作用 (NumberFormatException) 。我不知道如何实现这一点,最干净的方法是什么?


月关宝盒
浏览 95回答 2
2回答

qq_笑_17

如果 Long 不足以满足您的用例,那么您可以使用BigIntegerBigInteger(String val, int radix);它以字符串和基数作为参数。BigInteger result = new BigInteger(inputs[0], 2);for (int i = 1; i < inputs.length; i++) {&nbsp; &nbsp; result = result.and(new BigInteger(inputs[i], 2));}String resultStr = result.toString(2);

忽然笑

这是你的算法。这适用于任意数量的 ,Strings前提是所有Strings 的长度相同:public static void main(String[] args) {&nbsp; &nbsp; String a = "10110001";&nbsp; &nbsp; String b = "01101101";&nbsp; &nbsp; String c = "10101011";&nbsp; &nbsp; String arr[] = new String[]{a, b, c};&nbsp; &nbsp; String finalString = "";&nbsp; &nbsp; for (int i = 0; i < arr[0].length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; int temp = Integer.parseInt("" + arr[0].charAt(i));&nbsp; &nbsp; &nbsp; &nbsp; for (int j = 1; j < arr.length; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp = temp & Integer.parseInt("" + arr[j].charAt(i));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; finalString += temp;&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(finalString);}输出/输出00100001
随时随地看视频慕课网APP

相关分类

Java
我要回答