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?
5 Answers
s = s.replace('0', '2').replace('1', '0').replace('2', '1');
2 Comments
user3259851
Yes this worked. If you don't mind Can explain me how does it work?
JGFMK
@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!
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
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
Peter Lawrey
That will drop leading 000s
Naveen Ramawat
depends on the requirement. I don't think leading 000 has any meaning.
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
~operator does. Did you search for 1's complement?