Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
| 35. Search Insert Position | [Link](https://leetcode.com/problems/search-insert-position/) | [Link](./lib/easy/search_insert_position.dart) |
| 58. Length of Last Word | [Link](https://leetcode.com/problems/length-of-last-word/) | [Link](./lib/easy/length_of_last_word.dart) |
| 66. Plus One | [Link](https://leetcode.com/problems/plus-one/) | [Link](./lib/easy/plus_one.dart) |
| 67. Add Binary | [Link](https://leetcode.com/problems/add-binary/) | [Link](./lib/easy/add_binary.dart) |
48 changes: 48 additions & 0 deletions lib/easy/add_binary.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// https://leetcode.com/problems/add-binary/
class Solution {
String addBinary(String a, String b) {
var max = a.length > b.length ? a : b;
var min = max == a ? b : a;
var maxP = max.length - 1;
var minP = min.length - 1;
var result = [];
var add = 0;
while (minP >= 0) {
var maxC = max[maxP];
var minC = min[minP];
if (add == 1) {
result.add(maxC == minC ? '1' : '0');
if (maxC == '0' && minC == '0') {
add = 0;
}
} else {
if (maxC == '1' && minC == '1') {
add = 1;
result.add('0');
} else {
result.add(maxC == '1' || minC == '1' ? '1' : '0');
}
}
maxP--;
minP--;
}
while (maxP >= 0) {
var maxC = max[maxP];
if (add == 1 && maxC == '1') {
result.add('0');
} else {
if (add == 1) {
result.add('1');
add = 0;
} else {
result.add(maxC);
}
}
maxP--;
}
if (add == 1) {
result.add('1');
}
return result.reversed.join();
}
}
13 changes: 13 additions & 0 deletions test/easy/add_binary_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import 'package:leetcode_dart/easy/add_binary.dart';
import 'package:test/test.dart';

void main() {
group(
'Example tests',
() {
final ab = Solution();
test('100', () => expect('100', ab.addBinary('11', '1')));
test('10101', () => expect('10101', ab.addBinary('1010', '1011')));
},
);
}