Write a Java program to add two binary numbersInput Data:Input first binary number: 10Input second binary number: 11Expected Output
Sum of two binary numbers: 101
Sample Output:
Input first binary number: 100010 Input second binary number: 110010 Sum of two binary numbers: 1010100
import java.util.Scanner; public class Exercise17 { public static void main(String[] args) { long binary1, binary2; int i = 0, remainder = 0; int[] sum = new int[20]; Scanner in = new Scanner(System.in); System.out.print("Input first binary number: "); binary1 = in.nextLong(); System.out.print("Input second binary number: "); binary2 = in.nextLong(); while (binary1 != 0 || binary2 != 0) { sum[i++] = (int)((binary1 % 10 + binary2 % 10 + remainder) % 2); remainder = (int)((binary1 % 10 + binary2 % 10 + remainder) / 2); binary1 = binary1 / 10; binary2 = binary2 / 10; } if (remainder != 0) { sum[i++] = remainder; } --i; System.out.print("Sum of two binary numbers: "); while (i >= 0) { System.out.print(sum[i--]); } System.out.print("\n"); } }
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Sample Output:
need an explanation for this answer? contact us directly to get an explanation for this answer