233k views
4 votes
Java Programming Challenge Description: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. 0Input: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.Test 1Test InputDownload Test Input110011,1010Expected OutputDownload Test Output111101Test 2Test InputDownload Test Input11010,00101001Expected OutputDownload Test Output1000011

User Eyalb
by
5.5k points

1 Answer

5 votes

Answer:

import java.util.Scanner;

public class DecimalToBinary {

public static String convertToBinary(int n) {

if(n == 0) return "0";

String binary = "";

while (n > 0) {

binary = (n % 2) + binary;

n /= 2;

}

return binary;

}

public static int convertToDecimal(String binary) {

int n = 0;

char ch;

for(int i = 0; i < binary.length(); ++i) {

ch = binary.charAt(i);

n = n*2 + (ch - '0');

}

return n;

}

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

String[] words = in.nextLine().split(",");

System.out.println(convertToBinary(convertToDecimal(words[0].trim()) + convertToDecimal(words[1].trim())));

in.close();

}

}

Step-by-step explanation:

User Ersen Osman
by
6.3k points