-
Notifications
You must be signed in to change notification settings - Fork 0
/
addMultiBinary.java
46 lines (43 loc) · 1.49 KB
/
addMultiBinary.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.Scanner;
public class Exercise18 {
public static void main(String[] args) {
long binary1, binary2, multiply = 0;
int digit, factor = 1;
Scanner in = new Scanner(System.in);
System.out.print("Input the first binary number: ");
binary1 = in.nextLong();
System.out.print("Input the second binary number: ");
binary2 = in.nextLong();
while (binary2 != 0) {
digit = (int) (binary2 % 10);
if (digit == 1) {
binary1 = binary1 * factor;
multiply = binaryproduct((int) binary1, (int) multiply);
} else {
binary1 = binary1 * factor;
}
binary2 = binary2 / 10;
factor = 10;
}
System.out.print("Product of two binary numbers: " + multiply + "\n");
}
static int binaryproduct(int binary1, int binary2) {
int i = 0, remainder = 0;
int[] sum = new int[20];
int binary_prod_result = 0;
while (binary1 != 0 || binary2 != 0) {
sum[i++] = (binary1 % 10 + binary2 % 10 + remainder) % 2;
remainder = (binary1 % 10 + binary2 % 10 + remainder) / 2;
binary1 = binary1 / 10;
binary2 = binary2 / 10;
}
if (remainder != 0) {
sum[i++] = remainder;
}
--i;
while (i >= 0) {
binary_prod_result = binary_prod_result * 10 + sum[i--];
}
return binary_prod_result;
}
}