The code is an implementation of a method to obtain the two's complement of a binary number represented as a string. The main method calls the twosCompliment method, passing a binary number "01101100" as a string. The twosCompliment method then performs the following steps:
Finally, the twosCompliment method returns the two's complement of the input binary string as a string, which is printed to the console by the main method.
class Twos_Compliment { public static void main(String args[]) { System.out.print(twosCompliment("01101100")); } public static String twosCompliment(String bin) { String twos = "", ones = ""; for (int i = 0; i < bin.length(); i++) { ones += flip(bin.charAt(i)); } int number0 = Integer.parseInt(ones, 2); StringBuilder builder = new StringBuilder(ones); boolean b = false; for (int i = ones.length() - 1; i > 0; i--) { if (ones.charAt(i) == '1') { builder.setCharAt(i, '0'); } else { builder.setCharAt(i, '1'); b = true; break; } } if (!b) builder.append("1", 0, 7); twos = builder.toString(); return twos; } public static char flip(char c) { return (c == '0') ? '1' : '0'; } }
10010100
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions