Skip to content

Commit 7956534

Browse files
authored
Update Add Binary.java
1 parent c3cff36 commit 7956534

File tree

1 file changed

+13
-12
lines changed

1 file changed

+13
-12
lines changed

Easy/Add Binary.java

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
class Solution {
22
public String addBinary(String a, String b) {
3-
int carry = 0;
43
StringBuilder sb = new StringBuilder();
5-
int idxA = a.length() - 1;
6-
int idxB = b.length() - 1;
7-
while (idxA >= 0 || idxB >= 0 || carry > 0) {
8-
int temp = (
9-
(idxA >= 0 ? Character.getNumericValue(a.charAt(idxA--)) : 0) +
10-
(idxB >= 0 ? Character.getNumericValue(b.charAt(idxB--)) : 0) +
11-
carry
12-
);
13-
carry = temp > 1 ? 1 : 0;
14-
temp = temp > 1 ? (temp == 2 ? 0 : 1) : temp;
15-
sb.append(temp);
4+
int endIdxA = a.length() - 1;
5+
int endIdxB = b.length() - 1;
6+
int carry = 0;
7+
while (endIdxA >= 0 || endIdxB >= 0 || carry > 0) {
8+
int value = carry;
9+
if (endIdxA >= 0) {
10+
value += Character.getNumericValue(a.charAt(endIdxA--));
11+
}
12+
if (endIdxB >= 0) {
13+
value += Character.getNumericValue(b.charAt(endIdxB--));
14+
}
15+
sb.append(value % 2);
16+
carry = value / 2;
1617
}
1718
return sb.reverse().toString();
1819
}

0 commit comments

Comments
 (0)