In: Computer Science
use java Write a program that, given two binary numbers represented as strings, prints their sum in binary. The binary strings are comma separated, two per line. The final answer should not have any leading zeroes. In case the answer is zero, just print one zero i.e. 0
Input:
Your program should read lines from standard input. Each line contains two binary strings, separated by a comma and no spaces.
Output:
For each pair of binary numbers print to standard output their binary sum, one per line.
SOURCE CODE: *Please follow the comments to better understand the code. **Please look at the Screenshot below and use this code to copy-paste. ***The code in the below screenshot is neatly indented for better understanding. import java.util.Scanner; public class Addition { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); String[] numbers=scanner.nextLine().split(","); while(numbers[0].length()>0) // if the user enters empty line, break loop { //call the function System.out.println(numbers[0]+" + "+numbers[1]+" = "+add(numbers[0],numbers[1])); numbers=scanner.nextLine().split(","); } System.out.println("Good Bye!!"); } private static String add(String a, String b) { String answer=""; int sum=0; int i= a.length()-1; int j=b.length()-1; while (i >= 0 || j >= 0 || sum == 1) { // Compute sum of last digits and carry sum += ((i >= 0)? a.charAt(i) - '0': 0); sum += ((j >= 0)? b.charAt(j) - '0': 0); // If current digit sum is // 1 or 3, add 1 to result answer = (char)(sum % 2 + '0') + answer; // Compute carry sum /= 2; // Move to next digits i--; j--; } // remove leading zeroes String finalAnswer=""; for(int k=0;k<answer.length();k++) if(answer.charAt(k)=='1') { finalAnswer=answer.substring(k); break; } // check for answer= 0 if(finalAnswer=="") finalAnswer="0"; return finalAnswer; } }
=====================
SCREENSHOT:
OUTPUT