2

I need to combine an array of strings as below ( so as each character in the result string is a bitwise & of the characters in the input string)

String a = "10110001" String b = "01101101" String c = "10101011" String result = "00100001" 

Solution I came up with:

long resultLong = 0; for( String a : inputs ) { resultLong = resultLong & Long.parseLong( a ,2); } String result = Long.toBinaryString( resultLong ); 

The number of characters in the input string could be very long, and the above solution wouldn't work (NumberFormatException) . I couldn't get my head around how to implement this, what would be the cleanest way ?

2
  • 1
    How long is very long? Commented Sep 5, 2019 at 10:56
  • @khelwood 3600 characters Commented Sep 5, 2019 at 11:17

2 Answers 2

3

If Long is not enough for your use case then you can use BigInteger

BigInteger(String val, int radix); 

Which takes a String and radix as the arguments.

BigInteger result = new BigInteger(inputs[0], 2); for (int i = 1; i < inputs.length; i++) { result = result.and(new BigInteger(inputs[i], 2)); } String resultStr = result.toString(2); 
Sign up to request clarification or add additional context in comments.

4 Comments

This gives me the op 100001 for the input I have given in my question, so missing the leading 0's
@Chillax 100001 is the correct answer. You can pad it with leading zeroes if you need it to be of your expected length.
@khelwood Clear
It's nice to notice that the result can be computed bit per bit (or char per char, if you prefer), so the maximum length of numeric values shouldn't have anything to do with the answer...
0

Here's your algorithm. This will work for any number of Strings provided that all the Strings are of same length:

public static void main(String[] args) { String a = "10110001"; String b = "01101101"; String c = "10101011"; String arr[] = new String[]{a, b, c}; String finalString = ""; for (int i = 0; i < arr[0].length(); i++) { int temp = Integer.parseInt("" + arr[0].charAt(i)); for (int j = 1; j < arr.length; j++) { temp = temp & Integer.parseInt("" + arr[j].charAt(i)); } finalString += temp; } System.out.println(finalString); } 

O/P

00100001 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.