Skip to content

Commit e886484

Browse files
committed
solve problem Add Binary
1 parent cd0b832 commit e886484

File tree

5 files changed

+70
-0
lines changed

5 files changed

+70
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ All solutions will be accepted!
128128
|747|[Largest Number At Least Twice Of Others](https://leetcode-cn.com/problems/largest-number-at-least-twice-of-others/description/)|[java/py/js](./algorithms/LargestNumberAtLeastTwiceOfOthers)|Easy|
129129
|455|[assign cookies](https://leetcode-cn.com/problems/assign-cookies/description/)|[java/py/js](./algorithms/AssignCookies)|Easy|
130130
|415|[Add Strings](https://leetcode-cn.com/problems/add-strings/description/)|[java/py/js](./algorithms/AddStrings)|Easy|
131+
|67|[Add Binary](https://leetcode-cn.com/problems/add-binary/description/)|[java/py/js](./algorithms/AddBinary)|Easy|
131132

132133
# Database
133134
|#|Title|Solution|Difficulty|

algorithms/AddBinary/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Add Binary
2+
This problem is easy to solve, like problem Add Strings

algorithms/AddBinary/Solution.java

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public String addBinary(String a, String b) {
3+
String res = "";
4+
int carry = 0,
5+
i = a.length() - 1,
6+
j = b.length() - 1;
7+
8+
while (i >= 0 || j >= 0) {
9+
int x = i >= 0 ? a.charAt(i) - '0' : 0,
10+
y = j >= 0 ? b.charAt(j) - '0' : 0,
11+
sum = x + y + carry;
12+
13+
res = String.valueOf(sum % 2) + res;
14+
carry = sum / 2;
15+
i--;
16+
j--;
17+
}
18+
19+
return carry == 1 ? "1" + res : res;
20+
}
21+
}

algorithms/AddBinary/solution.js

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @param {string} a
3+
* @param {string} b
4+
* @return {string}
5+
*/
6+
var addBinary = function(a, b) {
7+
let res = '',
8+
carry = 0,
9+
i = a.length - 1,
10+
j = b.length - 1
11+
12+
while (i >= 0 || j >= 0) {
13+
let x = i >= 0 ? a[i] - '0' : 0,
14+
y = j >= 0 ? b[j] - '0' : 0,
15+
sum = x + y + carry
16+
17+
res = String(sum % 2) + res
18+
carry = parseInt(sum / 2)
19+
i--
20+
j--
21+
}
22+
23+
return carry ? '1' + res : res
24+
};

algorithms/AddBinary/solution.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution(object):
2+
def addBinary(self, a, b):
3+
"""
4+
:type a: str
5+
:type b: str
6+
:rtype: str
7+
"""
8+
res = ''
9+
carry = 0
10+
i = len(a) - 1
11+
j = len(b) - 1
12+
13+
while i >= 0 or j >= 0:
14+
x = ord(a[i]) - ord('0') if i >= 0 else 0
15+
y = ord(b[j]) - ord('0') if j >= 0 else 0
16+
sm = x + y + carry
17+
res = str(sm % 2) + res
18+
carry = sm / 2
19+
i -= 1
20+
j -= 1
21+
22+
return '1' + res if carry == 1 else res

0 commit comments

Comments
 (0)