Untitled

 avatar
unknown
plain_text
a year ago
2.9 kB
9
Indexable
import java.util.*;

class HelloWorld {
    public static void send(String msg) {
        int length = msg.length();
        StringBuilder temp = new StringBuilder(msg);
        StringBuilder num1 = new StringBuilder();
        StringBuilder num2 = new StringBuilder();
        int i = 0;
        
        // Splitting the message into two halves
        while (i < (length / 2)) {
            num1.append(msg.charAt(i));
            i++;
        }
        
        i = (length / 2);
        while (i < length) {
            num2.append(msg.charAt(i));
            i++;
        }
        
        String x = num1.toString();
        String y = num2.toString();
        // System.out.println("First half: " + x);
        // System.out.println("Second half: " + y);
        
        // Performing binary addition
        StringBuilder convert = new StringBuilder(addBinary(x, y));
        // System.out.println("Addition = " + convert);
        
        // Performing 1's complement
        String onecom = "";
        if (convert.length() == (x.length() + 1) && convert.charAt(0) == '1') {
            convert.deleteCharAt(0);
            String s = addBinary(convert.toString(), "1");
            // System.out.println("Binary addition of converted string and 1 is " + s);
            for (i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '0') {
                    onecom += '1';
                } else {
                    onecom += '0';
                }
            }
        } else {
            // 1s complement
            for (i = 0; i < convert.length(); i++) {
                if (convert.charAt(i) == '0') {
                    onecom += '1';
                } else {
                    onecom += '0';
                }
            }
        }
        
        // Appending the 1's complement to the original message
        temp.append(onecom);
        System.out.println("Output: " + temp);
    }
    
    public static String addBinary(String x, String y) {
        int i = x.length() - 1, j = y.length() - 1;
        int carry = 0;
        StringBuilder result = new StringBuilder();
        
        while (i >= 0 || j >= 0) {
            int sum = carry;
            if (i >= 0) {
                sum += x.charAt(i) - '0';
            }
            if (j >= 0) {
                sum += y.charAt(j) - '0';
            }
            
            result.append(sum % 2);
            carry = sum / 2;
            
            i--;
            j--;
        }
        
        if (carry != 0) {
            result.append(carry);
        }
        
        return result.reverse().toString();
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the message:");
        String msg = sc.nextLine();
        send(msg);
        sc.close();
    }
}
Editor is loading...
Leave a Comment