Skip to content

Commit 1681958

Browse files
authored
Merge pull request #887 from nilesh623/nilesh623-patch-1
Added Solution for LeetCode Problem No. 67
2 parents 03b0eee + a3565ba commit 1681958

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

LeetCode/67. Add Binary/Solution.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// https://leetcode.com/problems/add-binary/
2+
3+
class Solution {
4+
public String addBinary(String a, String b) {
5+
StringBuilder res = new StringBuilder();
6+
int i = a.length() - 1;
7+
int j = b.length() - 1;
8+
int carry = 0;
9+
while(i >= 0 || j >= 0){
10+
int sum = carry;
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);
15+
}
16+
if(carry != 0) res.append(carry);
17+
return res.reverse().toString();
18+
}
19+
}

0 commit comments

Comments
 (0)