Skip to content

Commit 2a7a880

Browse files
authored
Merge pull request #15 from fartem/67_Add_Binary
2023-02-08 update: added "67. Add Binary"
2 parents 58905ac + b957d5c commit 2a7a880

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
2424
| 35. Search Insert Position | [Link](https://leetcode.com/problems/search-insert-position/) | [Link](./lib/easy/search_insert_position.dart) |
2525
| 58. Length of Last Word | [Link](https://leetcode.com/problems/length-of-last-word/) | [Link](./lib/easy/length_of_last_word.dart) |
2626
| 66. Plus One | [Link](https://leetcode.com/problems/plus-one/) | [Link](./lib/easy/plus_one.dart) |
27+
| 67. Add Binary | [Link](https://leetcode.com/problems/add-binary/) | [Link](./lib/easy/add_binary.dart) |

lib/easy/add_binary.dart

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// https://leetcode.com/problems/add-binary/
2+
class Solution {
3+
String addBinary(String a, String b) {
4+
var max = a.length > b.length ? a : b;
5+
var min = max == a ? b : a;
6+
var maxP = max.length - 1;
7+
var minP = min.length - 1;
8+
var result = [];
9+
var add = 0;
10+
while (minP >= 0) {
11+
var maxC = max[maxP];
12+
var minC = min[minP];
13+
if (add == 1) {
14+
result.add(maxC == minC ? '1' : '0');
15+
if (maxC == '0' && minC == '0') {
16+
add = 0;
17+
}
18+
} else {
19+
if (maxC == '1' && minC == '1') {
20+
add = 1;
21+
result.add('0');
22+
} else {
23+
result.add(maxC == '1' || minC == '1' ? '1' : '0');
24+
}
25+
}
26+
maxP--;
27+
minP--;
28+
}
29+
while (maxP >= 0) {
30+
var maxC = max[maxP];
31+
if (add == 1 && maxC == '1') {
32+
result.add('0');
33+
} else {
34+
if (add == 1) {
35+
result.add('1');
36+
add = 0;
37+
} else {
38+
result.add(maxC);
39+
}
40+
}
41+
maxP--;
42+
}
43+
if (add == 1) {
44+
result.add('1');
45+
}
46+
return result.reversed.join();
47+
}
48+
}

test/easy/add_binary_test.dart

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import 'package:leetcode_dart/easy/add_binary.dart';
2+
import 'package:test/test.dart';
3+
4+
void main() {
5+
group(
6+
'Example tests',
7+
() {
8+
final ab = Solution();
9+
test('100', () => expect('100', ab.addBinary('11', '1')));
10+
test('10101', () => expect('10101', ab.addBinary('1010', '1011')));
11+
},
12+
);
13+
}

0 commit comments

Comments
 (0)