Skip to content

Commit 9d966a4

Browse files
solves add binary
1 parent 930551d commit 9d966a4

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Diff for: src/AddBinary.java

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import java.util.Scanner;
2+
3+
public class AddBinary {
4+
public static void main(String[] args) {
5+
Scanner scanner = new Scanner(System.in);
6+
String bin1 = scanner.next();
7+
String bin2 = scanner.next();
8+
System.out.println(addBinary(bin1, bin2));
9+
}
10+
11+
public static String addBinary(String a, String b) {
12+
Binary number1 = new Binary(a);
13+
Binary number2 = new Binary(b);
14+
return number1.add(number2).toString();
15+
}
16+
17+
private static class Binary {
18+
private final String number;
19+
20+
Binary(String number) {
21+
this.number = number;
22+
}
23+
24+
public int get(int index) {
25+
index = number.length() - index - 1;
26+
if (index < 0) {
27+
return 0;
28+
}
29+
return number.charAt(index) - 48;
30+
}
31+
32+
public int length() {
33+
return this.number.length();
34+
}
35+
36+
public Binary add(Binary other) {
37+
StringBuilder result = new StringBuilder();
38+
int carry = 0;
39+
for (int index = 0 ; index < Math.max(length(), other.length()) ; index++) {
40+
int value = this.get(index) + other.get(index) + carry;
41+
result.append(value % 2);
42+
carry = value / 2;
43+
}
44+
if (carry > 0) {
45+
result.append(carry);
46+
}
47+
return new Binary(result.reverse().toString());
48+
}
49+
50+
@Override
51+
public String toString() {
52+
return this.number;
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)