Skip to content

Commit 1802b86

Browse files
committed
Runtime: 1 ms (Top 100.0%) | Memory: 42.20 MB (Top 42.63%)
1 parent a17898a commit 1802b86

File tree

1 file changed

+12
-13
lines changed

1 file changed

+12
-13
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
1+
// Runtime: 1 ms (Top 100.0%) | Memory: 42.20 MB (Top 42.63%)
2+
13
class Solution {
24
public String addBinary(String a, String b) {
3-
StringBuilder sb = new StringBuilder();
5+
StringBuilder res = new StringBuilder();
6+
int i = a.length() - 1;
7+
int j = b.length() - 1;
48
int carry = 0;
5-
int i= a.length() -1;
6-
int j= b.length() -1;
7-
while(i>=0 || j>=0){
9+
while(i >= 0 || j >= 0){
810
int sum = carry;
9-
if(i>=0)
10-
sum+=a.charAt(i--)-'0'; // -'0' is just to convert char in integer
11-
if(j>=0)
12-
sum+=b.charAt(j--)-'0';
13-
sb.append(sum%2); // If we have sum = 1 1 then = 2 % 2 = 0 and 0 1 = 1 % 2 = 1
14-
carry = sum /2;
11+
if(i >= 0) sum += a.charAt(i--) - '0';
12+
if(j >= 0) sum += b.charAt(j--) - '0';
13+
carry = sum > 1 ? 1 : 0;
14+
res.append(sum % 2);
1515
}
16-
if(carry>0)
17-
sb.append(carry);
18-
return sb.reverse().toString();
16+
if(carry != 0) res.append(carry);
17+
return res.reverse().toString();
1918
}
2019
}

0 commit comments

Comments
 (0)