Skip to content

Commit e68b0cf

Browse files
committed
Solve the 'Add Binary' question
1 parent dfbe3ad commit e68b0cf

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package add_binary;
2+
3+
public class AddBinary {
4+
5+
public class Solution {
6+
public String addBinary(String a, String b) {
7+
StringBuilder re = new StringBuilder();
8+
int i = a.length() - 1;
9+
int j = b.length() - 1;
10+
int carry = 0;
11+
while (i >= 0 || j >= 0 || carry > 0) {
12+
int valueA = i < 0 ? 0 : a.charAt(i) - '0';
13+
int valueB = j < 0 ? 0 : b.charAt(j) - '0';
14+
re.append((valueA + valueB + carry) % 2);
15+
carry = (valueA + valueB + carry) / 2;
16+
i--;
17+
j--;
18+
}
19+
return re.reverse().toString();
20+
}
21+
}
22+
23+
public static class UnitTest {
24+
25+
}
26+
}

0 commit comments

Comments
 (0)