-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinaryAddition.java
More file actions
41 lines (35 loc) · 1.08 KB
/
BinaryAddition.java
File metadata and controls
41 lines (35 loc) · 1.08 KB
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
public class BinaryAddition {
public static String addBinaryStrings(String a, String b) {
StringBuilder result = new StringBuilder();
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
while (i>=0 || j>=0 || carry>0) {
int sum = 0;
if(carry==1)
sum++;
if (i >= 0 && a.charAt(i)=='1') sum++;
if (j >= 0 && b.charAt(j)=='1') sum++;
if (sum == 0) {
result.append('0');
carry = 0;
} else if (sum == 1) {
result.append('1');
carry = 0;
} else if (sum == 2) {
result.append('0');
carry = 1;
} else if (sum == 3) {
result.append('1');
carry = 1;
}
}
return result.reverse().toString();
}
public static void main(String[] args) {
String a = "1010";
String b = "1101";
String result = addBinaryStrings(a, b);
System.out.println("Sum: " + result);
}
}