Facebook
From Azra, 2 Months ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 203
  1. import java.util.Scanner;
  2.  
  3. public class BinaryAddition {
  4.     public static void main(String[] args) {
  5.         Scanner scanner = new Scanner(System.in);
  6.  
  7.         System.out.print("Enter the first binary string: ");
  8.         String a = scanner.nextLine();
  9.         System.out.print("Enter the second binary string: ");
  10.         String b = scanner.nextLine();
  11.  
  12.         String result = "";
  13.         int carry = 0;
  14.         int i = a.length() - 1;
  15.         int j = b.length() - 1;
  16.  
  17.         while (i >= 0 || j >= 0 || carry != 0) {
  18.             int total = carry;
  19.             if (i >= 0) {
  20.                 total += Character.getNumericValue(a.charAt(i));
  21.                 i--;
  22.             }
  23.             if (j >= 0) {
  24.                 total += Character.getNumericValue(b.charAt(j));
  25.                 j--;
  26.             }
  27.             result = total % 2 + result;
  28.             carry = total / 2;
  29.         }
  30.  
  31.         System.out.println("Binary sum: " + result);
  32.     }
  33. }
  34.