-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd Binary.java
More file actions
67 lines (60 loc) · 1.95 KB
/
Add Binary.java
File metadata and controls
67 lines (60 loc) · 1.95 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Solution {
public String addBinary(String a, String b) {
StringBuilder aword = new StringBuilder(a);
StringBuilder bword = new StringBuilder(b);
int alength = aword.length();
int blength = bword.length();
if (alength > blength) {
int gap = alength - blength;
while (bword.length() != aword.length()) {
bword.insert(0, '0');
}
} else {
int gap = blength - alength;
while (aword.length() != bword.length()) {
aword.insert(0, '0');
}
}
StringBuilder sb = new StringBuilder();
char carry = '0';
for (int i = bword.length() - 1; i >= 0; i--) {
if (aword.charAt(i) == '0' && bword.charAt(i) == '0') {
if (carry == '1') {
sb.insert(0, '1');
carry = '0';
} else {
sb.insert(0, '0');
}
}
else if (aword.charAt(i) == '0' && bword.charAt(i) == '1') {
if (carry == '1') {
sb.insert(0, '0');
carry = '1';
} else {
sb.insert(0, '1');
}
}
else if (aword.charAt(i) == '1' && bword.charAt(i) == '0') {
if (carry == '1') {
sb.insert(0, '0');
carry = '1';
} else {
sb.insert(0, '1');
}
}
else if (aword.charAt(i) == '1' && bword.charAt(i) == '1') {
if (carry == '1') {
sb.insert(0, '1');
carry = '1';
} else {
sb.insert(0, '0');
carry = '1';
}
}
}
if(carry =='1'){
sb.insert(0,'1');
}
return sb.toString();
}
}