2

I want to invert the bits in binary string. For example String 000 should be inverted as 111 and 1101 as 0010. Can anybody help on this?

2
  • 1
    That is what ~ operator does. Did you search for 1's complement? Commented Mar 25, 2014 at 8:13
  • Where are the bits stored? In what type? Commented Mar 25, 2014 at 8:14

5 Answers 5

10
s = s.replace('0', '2').replace('1', '0').replace('2', '1');
Sign up to request clarification or add additional context in comments.

2 Comments

Yes this worked. If you don't mind Can explain me how does it work?
@user3259851 If swaps 0's for 2's - so that when 1's are replaced with 0's you still have the 2's to then convert to 0's,, You need the intermediate 2, otherwise after replacing 0's with 1's you'd have a string of all 1's!
3

One way: is using the replaceAll() method:

String s = "01010";

s = s.replaceAll("0", "x");
s = s.replaceAll("1", "0");
s = s.replaceAll("x", "1");

System.out.println(s);

Output:

10101

Note:

This can be simplified chaining calls:

s = s.replaceAll("0", "x").replaceAll("1", "0").replaceAll("x", "1");

Comments

1

Check this, Here input is intger but you could easily convert your string into int I hope it will not be big task.

int i= 100;
System.out.println(Integer.toBinaryString(~i));

2 Comments

That will drop leading 000s
depends on the requirement. I don't think leading 000 has any meaning.
1

You can do this trick to swap 0 and 1

String s = "00011";
char[] chars = new char[s.length()];
for(int i = 0; i < s.length(); i++)
    chars[i] = (char) (s.charAt(i) ^ 1); // flip the bottom bit so 0=>1 and 1=>0
String flipped = new String(chars);
// flipped = "11100"

Comments

1

Using Apache commons-lang library you got a handy method to achieve this:

StringUtils.replaceChars(mystr, "01", "10");

Basically it replaces characters with corresponding characters (correspondence by index).

This is the litte test program

import org.apache.commons.lang.StringUtils;

public class InvertString {
    public static void main(String[] args) {
        System.out.println(invert("0001011"));
        System.out.println(invert("000"));
        System.out.println(invert("1101"));
    }

    private static String invert(String string) {
        return StringUtils.replaceChars(string, "01", "10");
    }
}

and the output of it is

1110100
111
0010

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.