Skip to content

Commit 33fb260

Browse files
authored
Java Program to Add two Binary Numbers
1 parent 7f1df0c commit 33fb260

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import java.util.Scanner;
2+
public class JavaExample {
3+
public static void main(String[] args)
4+
{
5+
//Two variables to hold two input binary numbers
6+
long b1, b2;
7+
int i = 0, carry = 0;
8+
9+
//This is to hold the output binary number
10+
int[] sum = new int[10];
11+
12+
//To read the input binary numbers entered by user
13+
Scanner scanner = new Scanner(System.in);
14+
15+
//getting first binary number from user
16+
System.out.print("Enter first binary number: ");
17+
b1 = scanner.nextLong();
18+
//getting second binary number from user
19+
System.out.print("Enter second binary number: ");
20+
b2 = scanner.nextLong();
21+
22+
//closing scanner after use to avoid memory leak
23+
scanner.close();
24+
while (b1 != 0 || b2 != 0)
25+
{
26+
sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2);
27+
carry = (int)((b1 % 10 + b2 % 10 + carry) / 2);
28+
b1 = b1 / 10;
29+
b2 = b2 / 10;
30+
}
31+
if (carry != 0) {
32+
sum[i++] = carry;
33+
}
34+
--i;
35+
System.out.print("Output: ");
36+
while (i >= 0) {
37+
System.out.print(sum[i--]);
38+
}
39+
System.out.print("\n");
40+
}
41+
}

0 commit comments

Comments
 (0)