-
Notifications
You must be signed in to change notification settings - Fork 0
/
addBinary.java
31 lines (28 loc) · 968 Bytes
/
addBinary.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
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");
}
}