File tree 1 file changed +41
-0
lines changed
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments