Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 6b1e252

Browse filesBrowse files
Sean PrashadSean Prashad
Sean Prashad
authored and
Sean Prashad
committed
Add 67_Add_Binary.java
1 parent 78a5705 commit 6b1e252
Copy full SHA for 6b1e252

File tree

Expand file treeCollapse file tree

1 file changed

+27
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+27
-0
lines changed

‎Strings/67_Add_Binary.java

Copy file name to clipboard
+27Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public String addBinary(String a, String b) {
3+
StringBuilder sb = new StringBuilder();
4+
int i = a.length() - 1, j = b.length() - 1, carry = 0;
5+
6+
while (i >= 0 || j >= 0) {
7+
int sum = carry;
8+
9+
if (i >= 0) {
10+
sum += a.charAt(i) - '0';
11+
--i;
12+
}
13+
if (j >= 0) {
14+
sum += b.charAt(j) - '0';
15+
--j;
16+
}
17+
18+
sb.append(sum % 2);
19+
carry = sum / 2;
20+
}
21+
22+
if (carry != 0) {
23+
sb.append(carry);
24+
}
25+
return sb.reverse().toString();
26+
}
27+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.