You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: easy/add-binary-67.md
+47-4Lines changed: 47 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -28,16 +28,59 @@ Output: "10101"
28
28
29
29
### Pseudocode
30
30
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
32
34
33
-
This solution has a time complexity
35
+
### Initial Attempt
34
36
35
-
```javascript
37
+
This solution has a time complexity O(a+b) however the solution doesn't work due to overflow.
36
38
39
+
```javascript
40
+
constaddBinary=function (a, b) {
41
+
constaDec=parseInt(a, 2);
42
+
constbDec=parseInt(b, 2);
43
+
constsum= aDec + bDec;
44
+
returnsum.toString(2);
45
+
};
37
46
```
38
47
39
48
### Optimized Solution
40
49
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
42
51
52
+
```javascript
53
+
constaddBinary=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
+
constaVal= a[aPoint] ?+a[aPoint] :0;
64
+
constbVal= 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
0 commit comments