Skip to content

Commit 20e22db

Browse files
Problem 67 (#18)
* add solution and resources * update readme
1 parent 64dc478 commit 20e22db

File tree

2 files changed

+48
-5
lines changed

2 files changed

+48
-5
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ As I work through this list I figure I would make a GitHub repo with my solution
2525
17. [Longest Palindrome #409](https://github.com/curtisbarnard/leetcode-grind75-javascript/blob/main/easy/longest-palindrome-409.md)
2626
18. [Reverse Linked List #206](https://github.com/curtisbarnard/leetcode-grind75-javascript/blob/main/easy/reverse-linked-list-206.md)
2727
19. [Majority Element #169](https://github.com/curtisbarnard/leetcode-grind75-javascript/blob/main/easy/majority-element-169.md)
28-
20. Add Binary #67
28+
20. [Add Binary #67](https://github.com/curtisbarnard/leetcode-grind75-javascript/blob/main/easy/add-binary-67.md)
2929
21. Diameter of Binary Tree #543
3030
22. Middle of the Linked List #876
3131
23. Maximum Depth of Binary Tree #104

easy/add-binary-67.md

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,59 @@ Output: "10101"
2828

2929
### Pseudocode
3030

31-
### Initial Solution
31+
1. Convert to decimal
32+
2. Add numbers
33+
3. Use toString method base 2 to convert to binary and return
3234

33-
This solution has a time complexity
35+
### Initial Attempt
3436

35-
```javascript
37+
This solution has a time complexity O(a+b) however the solution doesn't work due to overflow.
3638

39+
```javascript
40+
const addBinary = function (a, b) {
41+
const aDec = parseInt(a, 2);
42+
const bDec = parseInt(b, 2);
43+
const sum = aDec + bDec;
44+
return sum.toString(2);
45+
};
3746
```
3847

3948
### Optimized Solution
4049

41-
```javascript
50+
This solution has a time complexity of O(n) where n is the larger string and a space complexity of O(n). You can see an explanation of this approach here: https://www.youtube.com/watch?v=keuWJ47xG8g
4251

52+
```javascript
53+
const addBinary = function (a, b) {
54+
let result = '',
55+
carry = 0,
56+
aPoint = a.length - 1,
57+
bPoint = b.length - 1;
58+
59+
for (let i = 0; i < Math.max(a.length, b.length); i++) {
60+
let sum = carry;
61+
62+
// Make sure pointer is inbounds
63+
const aVal = a[aPoint] ? +a[aPoint] : 0;
64+
const bVal = b[bPoint] ? +b[bPoint] : 0;
65+
66+
// Update sum and carry based on division and modulo
67+
sum += aVal + bVal;
68+
carry = Math.floor(sum / 2);
69+
sum = sum % 2;
70+
71+
// Add to sum to front of result string
72+
result = String(sum) + result;
73+
74+
// Move to the next character left in each string
75+
aPoint--;
76+
bPoint--;
77+
}
78+
79+
// If any leftover carry add a 1 to beginning of result
80+
if (carry) {
81+
result = '1' + result;
82+
}
83+
84+
return result;
85+
};
4386
```

0 commit comments

Comments
 (0)