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.
THIS IS THE INPUT:
input 1: 110011,1010
input 2: 11010,00101001
THIS IS MY OUTPUT
out put 1: 111010
output 2: 01011011
THIS IS A DESIRE OUTPUT
output1: 111101
output2: 1000011
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; public class Main { /** * Iterate through each line of input. */ public static void main(String[] args) throws IOException { InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8); BufferedReader in = new BufferedReader(reader); StringBuilder sb = new StringBuilder(); String line; int i = 0; int j = 1; int sum; int carry = 0; int st_length1 = 0; int st_length2 = 0; String one = ""; String two =""; while ((line = in.readLine()) != null) { //System.out.println(line); String [] temp = line.split(","); one = new String( temp[0]); two = new String(temp[1]); } st_length1 = one.length() - 1; st_length2 = two.length() - 1; if(one == null || two == null) { return; } while(st_length1 > 0 || st_length2 > 0) { sum = carry; if (st_length1 > 0) { sum += one.charAt(st_length1) - '0'; st_length1--; } if(st_length2 > 0) { sum += two.charAt(st_length2) - '0'; st_length2--; } carry = sum >> 1; sum = sum & 1; sb.append(sum == 0 ? '0' : '1'); if (carry > 0) sb.append('1'); sb.reverse(); } System.out.println(sb.toString()); } }